Created
August 16, 2023 14:15
-
-
Save rambabu-patidar/6360e053dfce1aafcbb0583ec43636b9 to your computer and use it in GitHub Desktop.
Bubble sort resursive.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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