C/Data Structure Algorithm/Bubble Sort
A bigger bubble sort application
<source lang="cpp">
- include<stdio.h>
int bubble(int x[],int n) {
int hold,j,pass,i,switched = 1; for(pass = 0; pass < n-1 && switched == 1;pass++) { switched=0; for (j=0;j<n-pass-1;j++) if (x[j]>x[j+1]) { switched=1; hold = x[j]; x[j] = x[j+1]; x[j+1]=hold; } } return(0);
} int main() {
int marks[10]; int i; marks[0] = 39; marks[1] = 55; marks[2] = 43; marks[2] = 43; marks[3] = 49; marks[4] = 12; marks[5] = 2; marks[6] = 5; marks[7] = 4; marks[8] = 3; marks[9] = 1; bubble(marks, 10); for(i =0;i<10;i++){ printf("%d ",marks[i]); }
}
</source>
A bubble sort on int array
<source lang="cpp">
- include <stdio.h>
- include <stdlib.h>
int main(void) {
int item[100]; int a, b, t; int count; /* read in numbers */ printf("How many numbers? "); scanf("%d", &count); for(a = 0; a < count; a++) scanf("%d", &item[a]); /* now, sort them using a bubble sort */ for(a = 1; a < count; ++a) for(b = count-1; b >= a; --b) { /* compare adjacent elements */ if(item[ b - 1] > item[ b ]) { /* exchange elements */ t = item[ b - 1]; item[ b - 1] = item[ b ]; item[ b ] = t; } } /* display sorted list */ for(t=0; t<count; t++) printf("%d ", item[t]); return 0;
}
</source>
The Bubble Sort
<source lang="cpp">
- include <string.h>
- include <stdio.h>
- include <stdlib.h>
void bubble(char *items, int count); int main(void) {
char s[255]; printf("Enter a string:"); gets(s); bubble(s, strlen(s)); printf("The sorted string is: %s.\n", s); return 0;
}
void bubble(char *items, int count) {
register int i, j; register char t; for(i = 1; i < count; ++i) for( j = count-1; j >= i; --j) { if(items[j - 1] > items[ j ]) { /* exchange elements */ t = items[j - 1]; items[j - 1] = items[ j ]; items[ j ] = t; } }
}
</source>