Skip to content

Instantly share code, notes, and snippets.

@shahjugal
Last active July 18, 2022 03:06
Show Gist options
  • Save shahjugal/9ad3a7ea9bd3afeee1a285234a7c35c7 to your computer and use it in GitHub Desktop.
Save shahjugal/9ad3a7ea9bd3afeee1a285234a7c35c7 to your computer and use it in GitHub Desktop.
Selection Sort.
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