< Back to forum

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


Enter your answer details below:


Enter your comment details below:




1 Answer(s)

avatar

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)

Shubham_Kumar_Gupta last updated on April 7, 2019, 6:34 p.m. 0    Reply    Upvote   

Instruction to write good question
  1. 1. Write a title that summarizes the specific problem
  2. 2. Pretend you're talking to a busy colleague
  3. 3. Spelling, grammar and punctuation are important!

Bad: C# Math Confusion
Good: Why does using float instead of int give me different results when all of my inputs are integers?
Bad: [php] session doubt
Good: How can I redirect users to different pages based on session data in PHP?
Bad: android if else problems
Good: Why does str == "value" evaluate to false when str is set to "value"?

Refer to Stack Overflow guide on asking a good question.