Last active
July 18, 2022 03:06
-
-
Save shahjugal/9ad3a7ea9bd3afeee1a285234a7c35c7 to your computer and use it in GitHub Desktop.
Selection Sort.
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
void sortArray(vector<int>& nums) { | |
int lastIndex = nums.size() - 1; | |
// Run for Every Index except last one as it will be sorted anyways. | |
for (int runningIndex = 0; runningIndex < lastIndex; runningIndex++){ | |
// Find Minimum/Maximum from running index to lastIndex. | |
int min = runningIndex; | |
for(int i = runningIndex + 1; i <= lastIndex; i++){ | |
if(nums[i] < nums[min]){ | |
min = i; | |
} | |
} | |
// Place it in running index. | |
swap(nums[runningIndex], nums[min]); | |
} | |
} | |
// Finding both max and min and then placing min and max at i and lasstindex-i can be a optimaztion. | |
// Complexity will still be O(n^2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment