Sorting array

Hey I dont know what is wrong with my code. It can run but doesnt do what I want it to do, which is sorting values of array from small to large number. It just output random order which is weird.

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
28
29
30
31
32
33
34
35
36
37
#include <iostream>;
using namespace std;


int main() {
	float Feld[6];
	float Sp;
	int min = 0;
	int i = 0;

	cout << "Enter the value" << endl ;
	for (int i = 0; i < 6; i++) {
		cin >> Feld[i];
	}


	/*Sorting*/ 
	for (int i = 0; i < 6; i++) {
		for (int a = 1; a < 6; a++) { // comparation
			if (Feld[a] < Feld[i]) {
				min = a;
			}
			else min = i;
		}
		Sp = Feld[min];
		Feld[min] = Feld[i];
		Feld[i] = Sp;
	}


	for (int i = 0; i < 6; i++)
		cout << Feld[i] << "  ";

	system("pause");
	return 0; 

}
Last edited on
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
28
29
30
31
32
33
34
35
36
37
#include <iostream>
using namespace std;

int main() {

    const int N = 6 ; // number of elements in the array
    double Feld[N];

    std::cout << "Enter " << N << " numbers: ";
    for( int i = 0; i < N; ++i ) cin >> Feld[i];

    /*Sorting*/
    // algorithm: http://www.cs.armstrong.edu/liang/animation/web/SelectionSort.html
    // in each pass through this loop, we bring the smallest element in
    // the sub-array [i,N) to position i
    for( int i = 0; i < N; ++i ) {

        // invariant: items before position i are already sorted

        // for each unsorted sub-array starting at position i

        // locate the position of the smallest number in the sub-array starting at position i
        int pos_smallest = i ;
        // we look at each number after the number at position i
        for( int j = i+1; j < N ; ++j )
            if( Feld[j] < Feld[pos_smallest] ) pos_smallest = j ;

        // and bring the smallest number to position i (swap)
        const double smallest_number = Feld[pos_smallest] ;
        Feld[pos_smallest] = Feld[i] ;
        Feld[i] = smallest_number ;
    }

    // print out the sorted array
    for( int i = 0; i < N; ++i ) cout << Feld[i] << ' ' ;
    cout << '\n' ;
}
hey thanks Jlborges
Topic archived. No new replies allowed.