(HackerRank) Write a Modular C Programming code to solve Sort 3, Given an array sort all the elements except at index K. Display the array sorted except at index ‘K’
Given an array sort all the elements except at index K.
Input Format
First line contains ‘N’ the size of an array
Second line contains number of array elements
Third Line contains ‘K’, the index on which sorting shouldn’t be performed.
Constraints
N>0 and N<=10^5
0<=a[i]<=10^4
Output Format
Display the array sorted except at index ‘K’
Sample Input 0
-1
Sample Output 0
Invalid
Sample Input 1
5
50 40 10 20 30
2
Sample Output 1
20 30 10 40 50
Explanation 1
All the array elements are sorted excpet at index 2, 10 remains there, and all other elements get sorted.
Refer : C Programming HackerRank all solutions for Loops | Arrays | strings
CODE:
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> int main() { int n; scanf("%d",&n); if(n>0) { int array[n],i,j,k,temp; for(i=0;i<n;i++) { scanf("%d",&array[i]); } scanf("%d",&k); if(k==n-1) { for(i=0;i<n-1;i++) { for(j=0;j<n-2-i;j++) { if(array[j]>array[j+1]) { temp=array[j]; array[j]=array[j+1]; array[j+1]=temp; } } } } else{ for(i=0;i<n;i++) { for(j=0;j<n-1-i;j++) { if(j==k-1) { if(array[j]>array[j+2]) { temp=array[j]; array[j]=array[j+2]; array[j+2]=temp; } } else if(j!=k) { if(array[j]>array[j+1]) { temp=array[j]; array[j]=array[j+1]; array[j+1]=temp; } } } } } for(i=0;i<n;i++) { printf("%d ",array[i]); } } else{ printf("Invalid"); } return 0; }
OUTPUT
Congratulations, you passed the sample test case. Click the Submit Code button to run your code against all the test cases. Input (stdin) -1 Your Output (stdout) Invalid Expected Output Invalid
Please find some more codes of Loops, Condition Statements, 1D Arrays, 2D Arrays, Strings, Pointers, Data Structures, Files, Linked lists, MISC, Solved model question papers & Hacker Rank all solutions on the below page:
Top 100+ C Programming codes – KLE Technological University