Sorting
A sorting algorithm is used to rearrange a given array or
list of elements in an order.
For example,
Given array [10, 10, 5, 2] becomes [2, 5, 10, 10] after sorting
in increasing order.
There exist different sorting Algorithm:
1. Bubble sorting
2. Selection sorting
3. Insertion sorting
4. Merge sorting
5. Quick sorting
Bubble Sorting: Bubble Sorting is the simplest sorting that
works by repeatedly swapping the adjacent elements if
they are in the wrong order. This algorithm is not suitable
for large data sets as its time complexity are quite high
Now it works:
1. We sort the array using multiple passes. After the first
pass, the max element goes to end (it correct position).
Same way, after second pass, the second largest element
goes to second last position and so on.
2. In every pass, we process only those elements that have
already not moved to correct position. After k passes, the
largest k elements must have been moved to the last k
position.
3. In a pass, we consider remaining elements & compare all
adjacent & swap if larger element is before a smaller
element. If we keep doing this, we get the largest (among
the remaining elements) at its correct position.
Example:
Example:
#include <stdio.h>
#include <conio.h>
void bubble sort (int arr[], int n)
{
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j+1])
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
void print array (int arr[], int n)
{
for (int i = 0; i < n; i++)
{
printf ("%d", arr[i] );
}
printf ("\n");
}
int main()
{
int arr[] ={84,32,3,12}
int n =Size of (arr)/size of (arr[0]);
printf ("Original array :");
printArray(arr n);
bubbleSort(arr n);
printf ("Sorted array (Bubble Sort):");
printArray(arr n);
return 0;
}
Output:
Original array:{84,32,3,12}
Sorted array(Bubble Sort):{3,12,32,84}