Plz check whats wrong with the code for sorting an array??

sort an array

/uploads/ckeditor/attachments/7/Screenshot_20181010-204518.jpg

Proma
Proma Roy
Proma

Please Log in to answer

Note: Your answer should not be too short. Please wait a few seconds for the editor to load



Please make sure the answer is not too short

1 Answer

preda2or
preda2or 14:13, Oct 12
Shubham Kumar Gupta

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)




Please make sure the answer is not too short
0 Upvotes
Comments
No Comments yet