What is Bubble sort? Bubble sort is one of the basic and simple sorting techniques. Bubble sort is not advisable for huge amount of data. In today world, we may not be able to employ bubble sort technique because of the size of the data. But, learning a basic and easiest techniques will help us in improving our knowledge and will lay as foundation for further advanced techniques.
In this method, we sort the entire array by comparing each and every element with next element. If the next element is smaller than current element, then those two elements are swapped and if it is greater then left intact. For Bubble sort program in Java
The code below is self explanatory:
#include <stdio.h> #include <conio.h> void sort(int); void main(){ int size; printf("\n Enter size of the array: "); //Request for size of array scanf("%d",&size); sort(size); //Invoking sorting function with size as parameter getch(); }; void sort(int size){ int data[size],i,j,order,swap; for(i=0;i< size; i++){ printf("\n Enter data into the array: "); //Enter the data into the array scanf("%d",&data[i]); } printf("\n Enter for 1 for ascending order or 2 for descending order: "); // Ascending order or descending order scanf("%d",&order); if(order == 1){ /*Ascending order*/ for(i=0;i<size;i++){ for(j=0;j<size-1;j++){ if(data[j] > data[j+1]){ swap = data[j]; data[j] = data[j+1]; data[j+1] = swap; } } } } else { /*Descending order*/ for(i=0;i<size;i++){ for(j=0;j<size-1;j++){ if(data[j] < data[j+1]){ swap = data[j]; data[j] = data[j+1]; data[j+1] = swap; } } } } printf("\n Sorted data is:\n"); //Display of final sorted data for(i=0;i<size;i++){ printf("\t%d",data[i]); } }
Pingback: Insertion Sort in C | Letusprogram