/uploads/ckeditor/attachments/7/Screenshot_20181010-204518.jpg
Asked by: Proma_Roy on April 7, 2019, 6:34 p.m. Last updated on April 7, 2019, 6:34 p.m.
for each j-th iteration you are finding the next minimum value but you are missing the essential step of assigning that value to the current i-th index.
for array input :
5 9 10 7 4
your code does the following in the i-th iteration :
5 9 10 7 5 ( i = 0)
5 9 10 9 7 (i = 1)
5 9 10 10 9 (i = 2)
5 9 10 10 10 (i = 3)
5 9 10 10 10 (i = 4)
fix this by adding the following line :
for (int i = 0; i < t; ++i) {
int q = a[i];
for (int j = i; j < t; ++j) {
if (q > a[j]) {
int p = q;
q = a[j];
a[j] = p;
}
}
a[i] = q; // add this line
}
Now this is correct. Still i would recommend you to use inbuilt sort function in C++ as it is much faster than this selection sort algorithm.
complexity of selection sort : O(n ^ 2)
inbuilt sort function complexity : O(nlog(n))
to use the inbuilt sort function use the following code(assuming array name a and size n):
sort(a, a + n);
(NOTE : use header file #include<bits/stdc++.h> to use this sort function)