Advertisement
mydiaz

insertion sort

Apr 18th, 2022
749
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.07 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. int main(){
  4.     int A[10];
  5.     printf("Masukkan Elemen: \n");
  6.     for(int i = 0; i < 10; i++) {
  7.         scanf("%d", &A[i]);
  8.     }
  9.     int n = sizeof(A)/sizeof(A[0]);
  10.     printf("\Before Sorting : \n");
  11.     printArray(A, n);
  12.     InsertionSortAsc(A, n);
  13.     InsertionSortDesc(A, n);
  14.     return 0;
  15. }
  16.  
  17. void InsertionSortAsc(int A[], int n){
  18.     int i, key, j;
  19.     for(i=1; i<n; i++){
  20.         key = A[i];
  21.         j=i-1;
  22.         while(j >= 0 && A[j]>key){
  23.             A[j+1] = A[j];
  24.             j=j-1;;
  25.         }
  26.         A[j+1] = key;
  27.     }
  28.     printf("\nAfter Sorting Asc : \n");
  29.     printArray(A, n);
  30. }
  31.  
  32. void InsertionSortDesc(int A[], int n){
  33.     int i, key, j;
  34.     for(i=1; i<n; i++){
  35.         key = A[i];
  36.         j=i-1;
  37.         while(j >= 0 && A[j]<key){
  38.             A[j+1] = A[j];
  39.             j=j-1;;
  40.         }
  41.         A[j+1] = key;
  42.     }
  43.     printf("\nAfter Sorting Desc : \n");
  44.     printArray(A, n);
  45. }
  46.  
  47. void printArray(int A[], int n){
  48.     int i;
  49.     for(i=0; i<n; i++){
  50.         printf("%d ", A[i]);
  51.     }
  52.     printf("\n");
  53. }
  54.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement