This is a very basic method to sort an array works on swapping of adjacent elements if they are not in a order. we can sort array whether in ascending or descending order. suppose we have an array;
here length of array tell us how many time comparison and swapping takes place into the array arr.
First Loop:
Array After swapping of adjacent element
( 9, 5, 7, 4 ) => ( 5, 9, 7, 4 )
( 5, 9, 7, 4 ) => ( 5, 7, 9, 4 )
( 5, 7, 9, 4 ) => ( 5, 7, 4, 9 )
Second Loop:
Array After swapping of adjacent element
( 5, 7, 4, 9 ) => ( 5, 7, 4, 9 )
( 5, 7, 4, 9 ) => ( 5, 4, 7, 9 )
( 5, 4, 7, 9 ) => ( 5, 4, 7, 9 )
Third Loop:
Array After swapping of adjacent element
( 5, 4, 7, 9 ) => ( 4, 5, 7, 9 )
( 4, 5, 7, 9 ) => ( 4, 5, 7, 9 )
( 4, 5, 7, 9 ) => ( 5, 4, 7, 9 )
here is code given below as:
Program Code :
int* bubbleSort(int []); #define n 5 #include <stdio.h> int main() { int arr[n] = {9,5,1,2,0}, *pointer,arr2[n], i; pointer = bubbleSort(arr); //arr2 = &pointer; for(i = 0; i < n; i++ ){ printf("%d \n", *(pointer + i)); } return 0; } int* bubbleSort(int arr[n]){ int inc, inc2, tempI, tempVal; for(inc = 0; inc < n-1; inc++){ for(inc2 = inc+1; inc2 < n; inc2++ ){ tempI = arr[inc]; if(tempI > arr[inc2]){ tempVal = arr[inc2]; arr[inc2] = arr[inc]; arr[inc] = tempVal; } } } return arr; } Output: