insertion like cards |
An array A with N elements A[1], A[2] … A[N] is in memory
Insertion Sort scan A from A[1] to A[N] inserting each elements A[k] into its proper position in the previously sorted subarray A[1], A[2], …. A[K-1]
Pass 1: A[1] by itself is trivially sorted
Pass 2: A[2] is inserted either before or after A[1] so that A[1], A[2] is sorted
Pass 3: A[3] is inserted in its proper place in A[1], A[2], that is before A[1], between A[1] and A[2] or after A[2] so that A[1], A[2], A[3] is sorted
Pass 4: A[4] is inserted in its proper place in A[1], A[2], A[3] so that A[1], A[2], A[3], A[4] is sorted.
.
.
Pass N: A[N] is inserted in its proper place in A[1], A[2], A[3], .. A[N-1] so that A[1], A[2], A[3], A[4] , A[N] is sorted.
Insertion Sort Example :
Sort
an array A with 8 elements
77,
33, 44, 11, 88, 66, 55
Insertion Algorithm :
This algorithm sort an array with N elements[1] Set A[0] = -∞ [Initialize a delimiter]
[2] Repeat Steps 3 to 5 for K = 2, 3, …, N
[3] Set TEMP = A[K] and PTR = K-1
[4] Repeat while TEMP < A[PTR]
(a) Set A[PTR+1] = A[PTR]
(b) Set PTR = PTR -1
[5] Set A[PTR+1] = TEMP
[6] Exit
Complexity of Insertion Sort :
Worst Case: O(n^2)
Average Case: O(n^2)
Related Post : test
your programming skill P-2
C++ program :
- /*
- Insertion sort //most optimise algorithm
- beginer2cs.blogspot.com
- */
- #include<iostream>
- #include<malloc.h>
- using namespace std;
- main()
- {
- int *arr,n,i,j,key;
- cout<<"Number of element to sort : ";
- cin>>n;
- arr=(int*)malloc(sizeof(int)*n); //allocating space to array
- cout<<"Enter element of array \n";
- for(i=0;i<n;i++)
- cin>>*(arr+i); //taking input
- /********** insertion sort begin ************/
- for(j=1;j<n;j++) //start from second element
- {
- key=*(arr+j); //storing j'th element to temp variable
- i=j-1;
- while(i>=0 && key<*(arr+i))
- {
- *(arr+i+1)=*(arr+i);
- i--;
- }
- *(arr+i+1)=key ; //final position where key placed
- }
- /***************sorting complete ********************/
- //Print sorted array
- cout<<"sorted list \n ";
- for(i=0;i<n;i++)
- cout<<*(arr+i)<<" ";
- return 0;
- }
Output :
Related Post : Test
your Programming Skill : P-1
No comments:
Post a Comment
THANKS FOR UR GREAT COMMENT