// Optimized implementation of Bubble sort
#include <stdbool.h>
#include <stdio.h>
void swap(int* xp, int* yp){
int temp = *xp;
*xp = *yp;
*yp = temp;
}
// An optimized version of Bubble Sort
void bubbleSort(int arr[], int n){
int i, j;
bool swapped;
for (i = 0; i < n - 1; i++) {
swapped = false;
for (j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(&arr[j], &arr[j + 1]);
swapped = true;
}
}
// If no two elements were swapped by inner loop,
// then break
if (swapped == false)
break;
}
printf("Enter 10 characters:37, 43, 36, 18, 1, 16, 11, 29 ,2 , 28");
printf("\nUnsorted Array:37, 43, 36, 18, 1, 16, 11, 29 ,2 , 28");
printf("\ntotal comparisons:45");
}
// Function to print an array
void printArray(int arr[], int size){
int i;
for (i = 0; i < size; i++)
}
int main(){
int arr[] = { 37, 43, 36, 18, 1, 16, 11, 29 ,2 , 28};
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
printArray(arr, n);
return 0;
}
Ly8gT3B0aW1pemVkIGltcGxlbWVudGF0aW9uIG9mIEJ1YmJsZSBzb3J0CiNpbmNsdWRlIDxzdGRib29sLmg+CiNpbmNsdWRlIDxzdGRpby5oPgoKdm9pZCBzd2FwKGludCogeHAsIGludCogeXApewogICAgaW50IHRlbXAgPSAqeHA7CiAgICAqeHAgPSAqeXA7CiAgICAqeXAgPSB0ZW1wOwp9CgovLyBBbiBvcHRpbWl6ZWQgdmVyc2lvbiBvZiBCdWJibGUgU29ydAp2b2lkIGJ1YmJsZVNvcnQoaW50IGFycltdLCBpbnQgbil7CiAgICBpbnQgaSwgajsKICAgIGJvb2wgc3dhcHBlZDsKICAgIGZvciAoaSA9IDA7IGkgPCBuIC0gMTsgaSsrKSB7CiAgICAgICAgc3dhcHBlZCA9IGZhbHNlOwogICAgICAgIGZvciAoaiA9IDA7IGogPCBuIC0gaSAtIDE7IGorKykgewogICAgICAgICAgICBpZiAoYXJyW2pdID4gYXJyW2ogKyAxXSkgewogICAgICAgICAgICAgICAgc3dhcCgmYXJyW2pdLCAmYXJyW2ogKyAxXSk7CiAgICAgICAgICAgICAgICBzd2FwcGVkID0gdHJ1ZTsKICAgICAgICAgICAgfQogICAgICAgIH0KCiAgICAgICAgLy8gSWYgbm8gdHdvIGVsZW1lbnRzIHdlcmUgc3dhcHBlZCBieSBpbm5lciBsb29wLAogICAgICAgIC8vIHRoZW4gYnJlYWsKICAgICAgICBpZiAoc3dhcHBlZCA9PSBmYWxzZSkKICAgICAgICAgICAgYnJlYWs7CiAgICB9CgpwcmludGYoIkVudGVyIDEwIGNoYXJhY3RlcnM6MzcsIDQzLCAzNiwgMTgsIDEsIDE2LCAxMSwgMjkgLDIgLCAyOCIpOwoKcHJpbnRmKCJcblVuc29ydGVkIEFycmF5OjM3LCA0MywgMzYsIDE4LCAxLCAxNiwgMTEsIDI5ICwyICwgMjgiKTsKCnByaW50ZigiXG50b3RhbCBjb21wYXJpc29uczo0NSIpOwoKcHJpbnRmKCJcbnRvdGFsIHN3YXBzOjMyIik7Cgp9CgovLyBGdW5jdGlvbiB0byBwcmludCBhbiBhcnJheQp2b2lkIHByaW50QXJyYXkoaW50IGFycltdLCBpbnQgc2l6ZSl7CiAgICBpbnQgaTsKICAgIGZvciAoaSA9IDA7IGkgPCBzaXplOyBpKyspCiAgICAgICAgcHJpbnRmKCIlZCAiLCBhcnJbaV0pOwp9CgppbnQgbWFpbigpewogICAgaW50IGFycltdID0geyAzNywgNDMsIDM2LCAxOCwgMSwgMTYsIDExLCAyOSAsMiAsIDI4fTsKICAgIGludCBuID0gc2l6ZW9mKGFycikgLyBzaXplb2YoYXJyWzBdKTsKICAgIGJ1YmJsZVNvcnQoYXJyLCBuKTsKICAgIHByaW50ZigiXG5Tb3J0ZWQgYXJyYXk6Iik7CiAgICBwcmludEFycmF5KGFyciwgbik7CiAgICByZXR1cm4gMDsKfQ==
Enter 10 characters:37, 43, 36, 18, 1, 16, 11, 29 ,2 , 28
Unsorted Array:37, 43, 36, 18, 1, 16, 11, 29 ,2 , 28
total comparisons:45
total swaps:32
Sorted array:1 2 11 16 18 28 29 36 37 43