Advertisement
Shiam7777777

Untitled

Jan 19th, 2019
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.84 KB | None | 0 0
  1. // C program for insertion sort
  2. #include <stdio.h>
  3. #include <math.h>
  4.  
  5. /* Function to sort an array using insertion sort*/
  6. void insertionSort(int arr[], int n)
  7. {
  8. int i, key, j;
  9. for (i = 1; i < n; i++)
  10. {
  11.     key = arr[i];
  12.     j = i-1;
  13.  
  14.     /* Move elements of arr[0..i-1], that are
  15.         greater than key, to one position ahead
  16.         of their current position */
  17.     while (j >= 0 && arr[j] > key)
  18.     {
  19.         arr[j+1] = arr[j];
  20.         j = j-1;
  21.     }
  22.     arr[j+1] = key;
  23. }
  24. }
  25.  
  26. // A utility function to print an array of size n
  27. void printArray(int arr[], int n)
  28. {
  29. int i;
  30. for (i=0; i < n; i++)
  31.     printf("%d ", arr[i]);
  32. printf("\n");
  33. }
  34.  
  35.  
  36.  
  37. /* Driver program to test insertion sort */
  38. int main()
  39. {
  40.     int arr[] = {12, 11, 13, 5, 6};
  41.     int n = sizeof(arr)/sizeof(arr[0]);
  42.  
  43.     insertionSort(arr, n);
  44.     printArray(arr, n);
  45.  
  46.     return 0;
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement