Bubble Sort
Algorithm
Step1: Get array size and array from the user.
Step2: In the array, in each iteration, adjacent elements
will be compared.
Step3: If the preceding element is larger than the
succeeding element, the two elements will be swapped. If
not, the next pair of elements will be compared.
Step4: The arr of iterations of the outer loop will be
one less than the size of the of the array.
Flowchart
Program
#include<stdio.h>
#include<conio.h>
void Bubble_Sort(int arr[]);
main()
{
int arrlen;
printf("Enter length of array: ");
scanf("%d",&arrlen);
int arr[arrlen];
int i,j;
i=0;
while (i<arrlen)
{
printf("Enter %dth element of array: ",i);
scanf("%d",&arr[i]);
++i;
}
i=0;
printf("Your unsorted array is: ");
while (i<arrlen)
{
printf("%d ",arr[i]);
++i;
}
printf("\n");
Bubble_Sort(arr);
}
void Bubble_Sort(int arr[])
{
int len,temp,i,j;
len=sizeof(arr);
for(i=0; i<len-1; i++)
{
for(j=0; j<len-i-1; j++)
{
if(arr[j]>arr[j + 1])
{
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
printf("You bubble sorted array is: ");
i=0;
while (i<len)
{
printf("%d ",arr[i]);
++i;
}
}
Output
Conclusion
In this practical, we learnt how to write a program for
Bubble Sort, an array sorting method. It is the slowest
method of sorting with an average time complexity of O(n 2)
and a space complexity of O(n).
Quick Sort
Algorithm
Step1: Get array length and array from the user.
Step2: Let the element at index posn 0 be the pivot
element and i, and the last element be j.
Step3: Increment i posn till j>pivot.
Step4: Decrement j posn till it finds an element smaller
than the pivot. Now swap i and j.
Step5: Continue till i and j cross each other.
Step6: Now all elements with value less than pivot come
before it and all elements with value greater than it
come after it. The pivot is now at its final posn.
Step7: Apply steps 2 to 6 to the two subarrays (less than
and greater than pivot) till you get a sorted array.
Flowchart
Program
#include<stdio.h>
int main()
{
int i, arrlen;
i=0;
printf("Enter number of elements: ");
scanf("%d",&arrlen);
int arr[arrlen];
while (i<arrlen)
{
printf("Enter %dth element of array: ",i);
scanf("%d",&arr[i]);
++i;
}
Quick_Sort(arr,0,arrlen-1);
printf("Your Quick Sorted array is: ");
for(i=0;i<arrlen;i++)
printf(" %d",arr[i]);
return 0;
}
void Quick_Sort(int arr[],int first,int last)
{
int i, j, pivot, temp;
if(first<last)
{
pivot=first;
i=first;
j=last;
while(i<j)
{
while(arr[i]<=arr[pivot] && i<last)
i++;
while(arr[j]>arr[pivot])
{
j--;
}
if(i<j)
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
temp=arr[pivot];
arr[pivot]=arr[j];
arr[j]=temp;
Quick_Sort(arr,first,j-1);
Quick_Sort(arr,j+1,last);
}
}
Output
Conclusion
In this practical, we learned how to use Quick Sort as an
array sorting method. Quick sort is the fastest sorting
technique and has an average time complexity of O(n*logn)
and a space complexity of O(n).