Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- void insertionSort(int a[], int n){
- int i, j, element;
- for(i = 1; i < n; i++){ //Doesn't start from 0 because a list of one is already sorted
- element = a[i]; //Element is the number that will be put in the sorted part of array
- for(j = i; j > 0 && a[j-1] > element; j--) //index shifting from right to left
- a[j] = a[j-1]; //Element shifting from left to right
- a[j] = element; //Element is placed in the sorted list
- }
- }
- int main(){
- int *a, i, n;
- printf("How many numbers to sort?: ");
- scanf("%d", &n);
- a = (int *) malloc(sizeof(int) * n);
- printf("Enter %d numbers\n", n);
- for(i = 0; i<n; i++) scanf("%d", &a[i]);
- insertionSort(a, n);
- for(i = 0; i < n; i++) printf("\t%d\t", a[i]);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement