Selection sort(array)

In array, an element with highest value is first located, it is then replaced with last element. The procedure is repeated for all elements in array except last, and after that for all of them except the last two etc... until only one element is left in array. Its called an Selection Sort. I have an example of it and a question under the first code.





1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
using namespace std;
int main () {
    int N;
    float A[1000];
    do {
       cout << "N = ";
       cin >> N;
    } while (N < 2 || N > 1000);
    for (int i = 0; i < N; i++) {
        cout << "A[" << i << "] = ";
        cin >> A[i];
    }
    for (int i = N; i > 1; i--) {
        int Max = 0;
        for (int j = 1; j < i; j++)
            if (A[j] > A[Max]) Max  = j;
        float pom = A[i-1];
        A[i-1] = A[Max];
        A[Max] = pom;
    } 
    for (int i = 0; i < N; i++)
        cout << A[i] << " ";
    cout << endl;
    system("PAUSE");
    return 0;
}




How does nested for loop work...can u explain this whole part plz(and nested for loop in general)

1
2
3
4
5
6
7
8
9
 
for (int i = N; i > 1; i--) {
        int Max = 0;
        for (int j = 1; j < i; j++)
            if (A[j] > A[Max]) Max  = j;
        float pom = A[i-1];
        A[i-1] = A[Max];
        A[Max] = pom;
    } 



sry if eng is bad
I think i can explain.
I will start with the second loop
1
2
3
4
5
if (A[j] > A[Max]) Max  = j;
        float pom = A[i-1];
        A[i-1] = A[Max];
        A[Max] = pom;

what this does is simple it it checks if the j'th term is greater than the the j+1 th term.If it is then the the jth term gets switched with j+1 th term .
the first loops sees to it that whole process repeats to the size of array (ie
it repeats to a time to that number of elements in the array) to sort it many number of times to make it correct.

A nested loop is a loop which is initialized inside other loop.If u r interested visit these sites to learn more about this::

http://mathbits.com/MathBits/CompSci/looping/nested.htm
http://www.tutorialspoint.com/cplusplus/cpp_nested_loops.htm



thanx m8
Topic archived. No new replies allowed.