diff --git a/cpp/rasacharjee_bubbleSort.cpp b/cpp/rasacharjee_bubbleSort.cpp index f69dd62d..6e13d570 100644 --- a/cpp/rasacharjee_bubbleSort.cpp +++ b/cpp/rasacharjee_bubbleSort.cpp @@ -1,31 +1,41 @@ -#include -#define ll long long int +#include using namespace std; -// Bubble Sort -void bubbleSort(ll arr[], ll size) -{ - for (ll i = 0; i < size; i++) - { - for (ll j = i; j < size; j++) - { - if (arr[i] > arr[j]) - { - ll temp = arr[i]; - arr[i] = arr[j]; - arr[j] = temp; - } - } - } +void swapping(int &a, int &b) { //swap the content of a and b + int temp; + temp = a; + a = b; + b = temp; +} +void display(int *array, int size) { + for(int i = 0; i array[j+1]) { //when the current item is bigger than next + swapping(array[j], array[j+1]); + swaps = 1; //set swap flag + } + } + if(!swaps) + break; // No swap in this pass, so array is sorted + } +} +int main() { + int n; + cout << "Enter the number of elements: "; + cin >> n; + int arr[n]; //create an array with given number of elements + cout << "Enter elements:" << endl; + for(int i = 0; i> arr[i]; + } + cout << "Array before Sorting: "; + display(arr, n); + bubbleSort(arr, n); + cout << "Array after Sorting: "; + display(arr, n); } - -int main() -{ - ll arr[5] = {32, 8, 2, 5, 7}; - bubbleSort(arr, 5); - cout << "the array after bubble sort is\n"; - for (ll i = 0; i < 5; i++) - { - cout << arr[i] << " "; - } - return 0; -} \ No newline at end of file