Sorting and Searching
Sorting and Searching
Sorting and Searching
quick sort
selection sort
shell sort
Bubble sort – O(n2)
• It is called Bubble sort, because with each
iteration the smaller element in the list
bubbles up towards the first place, just like a
water bubble rises up to the water surface.
Void bubblesort(int a[], int n)
{for(i=0;i<n-1;i++)
{for(j=0;j<n-i-1;j++)
{ if(a[j]>a[j+1])
{ t=a[j];
a[j]=a[j+1];
a[j+1]=t; }}}}
Insertion sort - O(n2)
• Simple
• Efficient for small data compared to bubble
and selection
• Adaptive - reduces total number of steps if
given a partially sorted list, hence it increases
its efficiency.
• Stable - does not change the relative order of
elements with equal keys
• Best case – O(n)
void insertionsort (int a[], int n)
{for(i=1;i<=n-1;i++)
{ j=i;
x=a[i];
while(a[j-1]>x && j>0)
{ a[j]=a[j-1];
j=j-1; }
a[j]=x; }
}
Selection sort - O(n2)
• Simplest
void selectionsort (int elements[], int n)
{for (i=0;i<n-1; i++)
{min = i;
for (j = i+1;j<n; j++)
{if (elements[j] < elements[min])
min = j;}
temp = elements[i];
elements[i] = elements[min];
elements[min] = temp;}}
Shell Sort – O(n ) 2
int mid,i;
if(low<high)
{
mid=(low+high)/2;
printf("\nCalling MS low & mid with low=%d mid=%d",low,mid);
mergesort(k,low,mid);
printf("\nCalling MS mid + 1 & high with mid+1=%d high=%d",mid+1,high);
mergesort(k,mid+1,high);
for(i=low;i<=high;i++)
{
printf("%d \t",k[i]);
}
printf("\nCalling Merge fn with low=%d mid=%d high=%d\n\n",low,mid,high);
merge(k,low,mid,high);
}
}
//Routine for arranging in sorted order
void merge(int k[],int low,int mid,int high)
{ int i,j,temp[20],h;
i=low;
j=mid+1;
h=low;
while(i<=mid && j<=high)
{ if(k[i]<=k[j])
{temp[h]=k[i];
i=i+1; }
else
{temp[h]=k[j];
j=j+1; }
h++; }
if(i>mid)
{ while(j<=high)
{ temp[h]=k[j];
j=j+1;
h=h+1; } }
else
{ while(i<=mid)
{ temp[h]=k[i];
i=i+1;
h=h+1; }}
for(i=low;i<=high;i++)
{ k[i]=temp[i];}
}
Searching – Linear search O(n)
• Linear search
void linearsearch(int a[], int x, int n)
{int flag=0;
for(i=0;i<n;i++)
{
if(a[i]==x)
{ flag=1;
break;}}
if(flag==1)
print("\n The element is found at position %d\n",i+1);
else
print("\nElement notfound");
}
Binary Search
• Divide and Conquer technique
• Input elements should be in sorted order
Binary Search – O(logn)
mid=(low+high)/2;}
if(a[mid]==x)
print("Element found at position %d",mid+1);
else
print("Element not found");}