Array Sorting (2.3040923)

Dec 18, 2012 at 10:47pm
Im having problem with the fact that its not sorting the first number of the array into order? Also can you tell me what type of sort im using?

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
38
39
40
41
42
43
44
45
#include <iostream>
#include <string>
using namespace std;



int main()
{//array test
	int heights[10];
	for(int i=0; i<10; ++i)
	{
		cout << "\nEnter height for student " << i+1<<" ";
		cin >> heights[i];
	}

	for(int i=0;i<10;i++)
	{
		cout <<"\nHeight for student number "<<i+1<< " is " << heights[i] <<"cm";

	}


	system("PAUSE");

	//array test end

	for(int j=1;j<10;j++)
	{
		int key = heights[j];
		int i = j-1;

			while(i>0 && heights[i] > key)
			{heights[i+1]=heights[i];
			i=i-1;}
		heights[i+1] = key;
			}
	system("PAUSE");

	for(int x=0;x<10;x++)
	{
		cout <<"\n"<< heights[x];
	}
	system("PAUSE");
	return 0 ;
}
Dec 18, 2012 at 11:41pm
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <iostream>
#include <string>
using namespace std;



int main()
{
	//array test
	int heights[10];
	for(int i=0; i < 10; ++i)
	{
		cout << "\nEnter height for student " << i+1<<" ";
		cin >> heights[i];
	}

	for(int i = 0;i < 10; i++)
	{
		cout <<"\nHeight for student number "<< i + 1 << " is " << heights[i] <<"cm" << endl;;

	}
	//Selection sort
	int temp;
	int i, j;
	int smallest;
	int size = 10;
	for (i = 0; i < size - 1; i++)
	{
		smallest = i;

		for (j = i + 1; j < size; j++)
		{
			if( heights[j] <  heights[smallest] )
				{
					smallest = j;
				}
			
		}
			//swap
		    temp = heights[smallest];
			heights[smallest] = heights[i]; 
			heights[i] = temp;              
	}

	
    // To see sorted array
	for(int i = 0; i < 10; i++)
	{
		cout << heights[i] << " " ;

	}
	
	
	
	system("PAUSE");
	return 0 ;
}


Does this work better?
I used a high number like 58 for the first one. Then all the other values were lower and it seemed that it sorted it correctly. This is selection sort. I believe. I wrote it below with the variables above it . You should just make it a function it would be more appropriate I think. Well let me know if that is what you wanted.
Dec 18, 2012 at 11:51pm
thank you but I wanted to know why mine didn't work and what kind of sorting I used? . Ofcourse your one does work and thanks for your time
Dec 19, 2012 at 12:00am
Line 35 heights[i+1] = key;
The value key will be placed into the lowest element of the array when i+1 == 0. In order for that to be true, i must be equal to -1.

That cannot currently happen. The while loop at line 32 ends when i equals 0.
Solution, change line 32 to while (i>=0 && heights[i] > key)
Last edited on Dec 19, 2012 at 12:08am
Topic archived. No new replies allowed.