Bubble Sort

Explanation:

Code:

1
#include <stdio.h>
2
3
void bubbleSort(int data[], int len){
4
5
for(int i = 1; i < len; i++){
6
for(int j = 1; j < len; j++) {
7
if(data[j-1] > data[j]){
8
int tmp = data[j];
9
data[j] = data[j-1];
10
data[j-1] = tmp;
11
}
12
}
13
}
14
}
Copied!
Make it better:
1
void bubbleSort(int data[], int len){
2
for(int i = 1; i < len; i++){
3
for(int j = 1; j < len-i+1; j++) { <------------------!!!
4
if(data[j-1] > data[j]){
5
int tmp = data[j];
6
data[j] = data[j-1];
7
data[j-1] = tmp;
8
}
9
}
10
}
11
}
Copied!

Test code:

1
int main(void){
2
3
int data[] = { -1, 0, 7, -9, 8, -99};
4
5
int len = sizeof(data)/sizeof(data[0]);
6
bubbleSort(data, len);
7
8
for (int t = 0; t < len; t++)
9
printf("data[%d] = %d \n", t, data[t]);
10
11
return 0;
12
}
Copied!
Copy link