Examples:
Input: arr[] = {10, 9, 8, 7, 4, 70, 60, 50}
k = 4
Output: arr[] = {4, 7, 8, 9, 10, 50, 60, 70}
Input: arr[] = {6, 5, 3, 2, 8, 10, 9}
k = 3
Output: arr[] = {2, 3, 5, 6, 8, 9, 10}
We can use Insertion Sort to sort the elements efficiently.
#include <bits/stdc++.h>
using namespace std;
// performs Insertion Sort
void insertionSort(int array[], int N, int K)
{
int i, temp, j;
// start from index 1
for (i = 1; i < N; i++)
{
// store current element in temp
temp = array[i];
j = i - 1;
// Move the temp element until
// its previous element is greater
// or index is 0
while (j >= 0 && array[j] > temp)
{
array[j + 1] = array[j];
j = j - 1;
}
// assign the temp value
// to correct index
array[j + 1] = temp;
}
}
// Function to print the array
void printArray(int array[], int length)
{
for (int i = 0; i < length; i++)
cout << array[i] << " ";
cout << endl;
}
// Main function
int main()
{
int array[100], N, K;
cout << "Enter Number of elements: ";
cin >> N;
for (int i = 0; i < N; i++)
{
cin >> array[i];
}
cout << "Enter the value of K: ";
cin >> K;
insertionSort(array, N, K);
cout << "Sorted Array" << endl;
printArray(array, N);
return 0;
}
Output:
Enter Number of elements: 8
10 9 8 7 4 80 50 60
Enter the value of K: 4
Sorted Array
4 7 8 9 10 50 60 80
0 Comments