Sorting Techniques - NOTES
Sorting Techniques - NOTES
h" void main() { clrscr(); int a[5],i,j,t; cout<<"\n\nEnter the Elements in an Array"; for(i=0;i<5;i++) { cin>>a[i]; } for(i=0;i<5;i++) { for(j=0;j<5-1-i;j++) { if(a[j]>a[j+1]) { t=a[j]; a[j]=a[j+1]; a[j+1]=t; } } } cout<<"\n\nSorted Arrays is as Follows"; for(i=0;i<5;i++) { cout<<a[i]<<"\n"; } }
//Program to sort an array using Selection Sort Teachnique. #include"iostream.h" #include"conio.h" void main() { clrscr(); int a[5],i,j,t,s,pos; cout<<"\n\nEnter the Elements in an Array"; for(i=0;i<5;i++) { cin>>a[i]; } for(i=0;i<5;i++) { s=a[i]; pos=i; for(j=i+1;j<5;j++) { if(a[j]<s) { s=a[j]; //finding smallest no. pos=j; //storing position of smallest element } } t=a[i]; //swapping nos. located at i position with a[i]=a[pos]; //nos. located at pos(lowest no) positions a[pos]=t; } cout<<"\n\nSorted Arrays is as Follows"; for(i=0;i<5;i++) { cout<<a[i]<<"\n"; } }
//Program to merge two arrays into 3rd array assuming both arrays in ascending order and resultant array in ascending order #include"iostream.h" #include"conio.h" void main() { clrscr(); int a[5],b[5],c[10],i,j,k=0; cout<<"\n\nEnter Elements in First Array"; for(i=0;i<5;i++) { cin>>a[i]; } cout<<"\n\nEnter Elements in Second Array"; for(i=0;i<5;i++) { cin>>b[i]; } i=j=0; while(i<5&&j<5) { if(a[i]<b[j]) { c[k++]=a[i++]; } else { c[k++]=b[j++]; } } if(i==5) { for(;j<5;j++) { c[k++]=b[j]; } } if(j==5) { for(;i<5;i++) { c[k++]=a[i]; } } cout<<"\n\nNow the Merged Array is as follows:"; for(i=0;i<10;i++) { cout<<c[i]<<"\n"; } }
//Program to merge two arrays into 3rd array assuming 1st array in asc order & 2nd array in desc order and resultant array in ascending order #include"iostream.h" #include"conio.h" void main() { clrscr(); int a[5],b[5],c[10],i,j,k=0; cout<<"\n\nEnter Elements in First Array"; for(i=0;i<5;i++) { cin>>a[i]; } cout<<"\n\nEnter Elements in Second Array"; for(i=0;i<5;i++) { cin>>b[i]; } i=0,j=4; while(i<5&&j>0) { if(a[i]<b[j]) { c[k++]=a[i++]; } else { c[k++]=b[j--]; } } if(i==5) { for(;j>=0;j--) { c[k++]=b[j]; } } if(j==0) { for(;i<5;i++) { c[k++]=a[i]; } } cout<<"\n\nNow the Merged Array is as follows:"; for(i=0;i<10;i++) { cout<<c[i]<<"\n"; } }