Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Bubble Sort using C

 Bubble Sort is one of the most popular sorting methods. It can be treated as a selection sort because it is based on successively selecting the smallest element, second smallest element and so on.


In order to find the successive smallest elements this process relies heavily on the exchange of the adjacent elements and swaps them if they are in the wrong order.



Time Complexity

Bubble sort has worst-case and average complexity both О(n2), where n is the number of items being sorted.


Bubble Sort using C

The complete source code using C program is given below:

/* 
* File: BubbleSort.c
*/


#include
#include

void bubbleSort(int a[], int n) {
int i, j, k;
int temp;
for (i = 0; i n; i++) {
j
= n - 1;
k
= 0;
while (j > i) {
if (a[j] a[j - 1]) {
temp
= a[j];
a
[j] = a[j - 1];
a
[j - 1] = temp;
k
= 1;
}
j
--;
}
if (k == 0) {
break;
}
}
printf
("\n");
printf
("\nThe Sorted Array Elements are given below\n");
for (i = 0; i n; i++) {
printf
("a[%d]=%d ", i, a[i]);
}
}

int main() {
int i, n = 6;
int a[] = {15, 8, 17, 12, 38, 19};
printf
("\n:: Bubble Sort ::\n");
printf
("\nInput array elements\n");
for (i = 0; i n; i++) {
printf
("a[%d]=%d ", i, a[i]);
}
bubbleSort
(a, n);
}


Testing the Program

By executing the above program we will get below output:

:: Bubble Sort ::

Input array elements
a
[0]=15 a[1]=8 a[2]=17 a[3]=12 a[4]=38 a[5]=19

The sorted array elements are given below
a
[0]=8 a[1]=12 a[2]=15 a[3]=17 a[4]=19 a[5]=38





This post first appeared on PHP Update Data In MySQL Database, please read the originial post: here

Share the post

Bubble Sort using C

×

Subscribe to Php Update Data In Mysql Database

Get updates delivered right to your inbox!

Thank you for your subscription

×