Skip to content

Commit f3e32e4

Browse files
authored
Merge pull request #21 from vikkastiwari/patch-1
added condition - It restricts unwanted execution
2 parents 12cde1e + 99f0b01 commit f3e32e4

File tree

1 file changed

+23
-14
lines changed

1 file changed

+23
-14
lines changed

SortingAlgorithms/selectionSort/main.cpp

Lines changed: 23 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3,36 +3,45 @@
33
Time Complexity = O(n^2)
44
Space Complexity = O(1)
55
*/
6-
#include<iostream>
6+
#include <bits/stdc++.h>
77
using namespace std;
88

9-
void swapFunction(int *num1, int *num2) {
9+
void swap(int *num1, int *num2)
10+
{
1011
int temp = *num1;
1112
*num1 = *num2;
1213
*num2 = temp;
1314
}
1415

15-
void selectionSort(int arr[], int n) {
16-
for(int i = 0; i < n - 1; i++) {
17-
int min_index = i;
18-
for(int j = i + 1; j < n; j++) {
19-
if(arr[j] < arr[min_index]) {
20-
min_index = j;
16+
void selectionSort(int arr[], int n)
17+
{
18+
for (int i = 0; i < n - 1; i++)
19+
{
20+
int minIndex = i;
21+
for (int j = i + 1; j < n; j++)
22+
{
23+
if (arr[j] < arr[minIndex])
24+
{
25+
minIndex = j;
2126
}
2227

23-
swapFunction(&arr[min_index], &arr[i]); // swap the minimum index element and first index element
28+
// swap the minimum index element and first index element
29+
if (minIndex != i)
30+
swap(&arr[minIndex], &arr[i]);
2431
}
2532
}
2633
}
2734

28-
int main() {
35+
int main()
36+
{
2937
int arr[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
30-
int n = sizeof(arr)/sizeof(arr[0]);
38+
int n = sizeof(arr) / sizeof(arr[0]);
3139

3240
selectionSort(arr, n);
33-
cout<<"Sorted Array is: ";
34-
for(int i = 0; i < n; i++) {
35-
cout<<arr[i]<<" ";
41+
cout << "Sorted Array is: ";
42+
for (int i = 0; i < n; i++)
43+
{
44+
cout << arr[i] << " ";
3645
}
3746

3847
return 0;

0 commit comments

Comments
 (0)