Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Print n smallest elements from given array in their original order
Given an array of elements, the program must find the n smallest elements and display them in their original order of appearance in the array.
Input : arr[] = {1, 2, 4, 3, 6, 7, 8}, k=3
Output : 1, 2, 3
Input k is 3 it means 3 smallest elements among the set needs to be displayed in original order like 1 than 2 and than 3
Syntax
void findNSmallest(int arr[], int size, int k);
Algorithm
START
Step 1 −> start variables as int i, max, pos, j, k=4 and size for array size
Step 2 −> Loop For i=k and i<size and i++
Set max = arr[k-1]
pos = k-1
Loop For j=k-2 and j>=0 and j--
If arr[j]>max
Set max = arr[j]
Set pos = j
End
End
IF max> arr[i]
Set j = pos
Loop While j < k-1
Set arr[j] = arr[j+1]
Set j++
End
Set arr[k-1] = arr[i]
End IF
End
Step 3 −> Loop For i = 0 and i < k and i++
Print arr[i]
STOP
Example
This approach uses a modified insertion sort to maintain the k smallest elements in their original order −
#include <stdio.h>
int main() {
int arr[] = {5, 8, 3, 1, 2, 9};
int i, max, pos, j, k = 4;
int size = sizeof(arr) / sizeof(arr[0]);
printf("Original array: ");
for(i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("
");
// Using insertion sort, starting from k
for(i = k; i < size; i++) {
max = arr[k-1];
pos = k-1;
for(j = k-2; j >= 0; j--) {
if(arr[j] > max) {
max = arr[j];
pos = j;
}
}
if(max > arr[i]) {
j = pos;
while(j < k-1) {
arr[j] = arr[j+1];
j++;
}
arr[k-1] = arr[i];
}
}
// Printing first k elements
printf("The %d smallest elements in original order: ", k);
for(i = 0; i < k; i++) {
printf("%d ", arr[i]);
}
printf("
");
return 0;
}
Output
Original array: 5 8 3 1 2 9 The 4 smallest elements in original order: 5 3 1 2
How It Works
- The algorithm maintains a window of the first k elements as potential candidates.
- For each remaining element, it finds the maximum element in the current k-element window.
- If the current element is smaller than this maximum, it replaces the maximum while preserving order.
- The shifting operation maintains the original relative order of elements.
Conclusion
This approach efficiently finds the n smallest elements while preserving their original order using a modified insertion sort technique with O(n*k) time complexity.
Advertisements
