sorting technique
TRANSCRIPT
SORTING ALGORITHMS
Engr. Shaheer Ahmed
ALGO - INSERTION SORT (N, A)A : ArrayN : Length of Array A[]
Start AlgoFor i:=1 to N-1 do value := A[i] j := i-1 while j >= 0 and A[j] > value do A[j+1] := A[j] j := j-1 endwhile A[j+1] = value EndforEnd Algo
Program – Insertion Sort#include<iostream>using namespace std;
main(){int A[6] = {6,5,4,3,2,1};int N=6;int i,j,val;
for(i=1;i<N;i++) { val=A[i]; j=i-1;
while(j>=0 && A[j]>val) { A[j+1]=A[j]; j=j-1; } A[j+1]=val; }cout<<endl;
for(int i = 0 ; i<N ; i++)cout<<A[i]<<" "; system("pause");}
Insertion Sort
Worst case analysis of Insertion Sort
Apply Insertion Sort on the following Data: 7,6,5,4,3,2,1
Selection Sort
Program – Selection Sort#include<iostream>using namespace std;
main(){int A[6] = {5,2,6,4,3,1};int N=6;int i,sel=0,min,index,swap=0, temp;
//Find smallest number and swap with selected index with each iteration of outer loop
while(sel<N){min = A[sel];for(i = sel; i< N; i++){ if(A[i]<min) //if smaller number is found { min=A[i]; index=i; // save index of smaller number swap=1; // swapping required.. } }//swapping if(swap==1){A[sel] = A[sel] + A[index]; // a = a+bA[index] = A[sel] - A[index]; // b = a - bA[sel] = A[sel] - A[index]; // a = a-b}
sel++;swap=0;}
for(int i = 0 ; i<N ; i++)cout<<A[i]<<" ";
system("pause");}
Apply Selection Sort on the following Data:7,6,5,4,3,2,1
Worst case analysis of Selection Sort
Quick Sort15 20 35 10 25 55 50 45 40 30
3015 20 10 25 35 55 50 45 40
3015 20 2510 4535 40 50 55
15 2010 25 35 4540 50 55
10 15 20 25 30 35 40 45 50 55
30
MERGE SORT
15 , 20 , 35 , 10 , 25 , 55 , 50 , 45
15 20 10 35 25 55 45 50
10 15 20 35 25 45 50 55
10 15 20 25 35 45 50 55
GIVEN DATA