-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathnearly_sorted_algorithm.c
More file actions
48 lines (39 loc) · 865 Bytes
/
nearly_sorted_algorithm.c
File metadata and controls
48 lines (39 loc) · 865 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
Nearly Sorted Algorithm
Problem Link: https://practice.geeksforgeeks.org/problems/nearly-sorted-algorithm/0
Author: Shyam Kumar
*/
#include <stdio.h>
#include <stdlib.h>
void nearly_sorted_array( int *arr, int n, int k ) {
int i, j, temp;
for( i = 1; i < n; i++ ) {
temp = arr[i];
for( j = i-1; j >= i-k; j-- ) {
if( arr[j] > temp ) {
arr[j+1] = arr[j];
}
else
break;
}
arr[j+1] = temp;
}
}
int main(void) {
int t, n, k, i;
printf("Enter the number of test Cases: ");
scanf("%d",&t);
while(t--) {
printf("Enter the value of n and k: ");
scanf("%d %d", &n, &k);
int *arr = (int*)malloc( n * sizeof(int) );
printf("Enter the array: ");
for( i = 0; i < n; i++ )
scanf("%d",&arr[i]);
nearly_sorted_array( arr, n, k );
// Printing the array
for( i = 0; i < n; i++ ) {
printf("%d ",arr[i]);
}
}
}