Advertisement
Shailrshah

Insertion Sort

Oct 8th, 2013
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.74 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. void insertionSort(int a[], int n){
  4.     int i, j, element;
  5.     for(i = 1; i < n; i++){ //Doesn't start from 0 because a list of one is already sorted
  6.         element = a[i]; //Element is the number that will be put in the sorted part of array
  7.         for(j = i; j > 0 && a[j-1] > element; j--) //index shifting from right to left
  8.             a[j] = a[j-1]; //Element shifting from left to right
  9.         a[j] = element; //Element is placed in the sorted list
  10.     }
  11. }
  12. int main(){
  13.     int *a, i, n;
  14.     printf("How many numbers to sort?: ");
  15.     scanf("%d", &n);
  16.     a = (int *) malloc(sizeof(int) * n);
  17.     printf("Enter %d numbers\n", n);
  18.     for(i = 0; i<n; i++) scanf("%d", &a[i]);
  19.     insertionSort(a, n);
  20.     for(i = 0; i < n; i++) printf("\t%d\t", a[i]);
  21. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement