Skip to content

Instantly share code, notes, and snippets.

@rambabu-patidar
Created August 16, 2023 14:15
Show Gist options
  • Save rambabu-patidar/6360e053dfce1aafcbb0583ec43636b9 to your computer and use it in GitHub Desktop.
Save rambabu-patidar/6360e053dfce1aafcbb0583ec43636b9 to your computer and use it in GitHub Desktop.
Bubble sort resursive.
#include<bits/stdc++.h>
using namespace std;
void swap(vector<int>& nums, int i, int j)
{
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
int times = 0;
void bubbleSort(vector<int>&nums, int i, int j, int count) {
if (i == -1 && j == 0) {
return;
}
if (i >= j) {
// bool swapped = true;
bool swapped = false; // ** comment this line
if (nums[j] > nums[j + 1]) {
swap(nums, j, j + 1);
swapped = true;
}
// times++;
bubbleSort(nums, i, j + 1, swapped ? count + 1: count);
} else {
if (count == 0) {
return;
}
times++;
bubbleSort(nums, i - 1, 0, 0);
}
}
int main(){
vector<int> nums = {1, 2, 3, 4};
bubbleSort(nums, nums.size() - 2, 0, 0);
for (int num: nums) {
cout << num << " ";
}
cout << endl << "Times " << times << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment