algorithm:
void bubbleSort(int arr[], int n) { int i, j; for (i = 0; i < n-1; i++) for (j = 0; j < n-i-1; j++) if (arr[j] > arr[j+1]) swap(&arr[j], &arr[j+1]); }
You can also use the bit operator to swap two elements:
for(int i = 0; i<q; i++){ for(int j = 0; j<q-1; j++){ if(a[j]>a[j+1]){ a[j] ^= a[j+1]; a[j+1] ^= a[j]; a[j] ^= a[j+1]; } } }
Example:
// Bubble sort using C language #include <stdio.h> void swap(int *xp, int *yp) { int temp = *xp; *xp = *yp; *yp = temp; } // A function that implements bubble sort void bubbleSort(int arr[], int n) { int i, j; for (i = 0; i < n-1; i++) for (j = 0; j < n-i-1; j++) if (arr[j] > arr[j+1]) swap(&arr[j], &arr[j+1]); } // Print the array void printArray(int arr[], int size) { int i; for (i=0; i < size; i++) printf("%d ", arr[i]); printf("\n"); } int main() { int arr[] = {64, 34, 25, 12, 22, 11, 90}; int n = sizeof(arr)/sizeof(arr[0]); printf("before sorted: \n"); printArray(arr, n); bubbleSort(arr, n); printf("after sorted: \n"); printArray(arr, n); return 0; }