Ascending, descending sorting wrong numbers

Hi,

I've got a problem with my code. It should show the random numbers in descending and ascending order, however sometimes it shows 0 at the first position in ascending order (even if min is higher) and sometimes it shows some weird big number in descending order. I think it has to do with the number of numbers in tab. Could somebody explain to me why this happens and what can I do with it?

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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
  #include <iostream>
#include <ctime>
#include <cstdlib>
#include <stdio.h>
using namespace std;

 
int main () 
{
  
srand (time (NULL));
  
int min, max, size;
  
cout << "min: ";
  
cin >> min;

cout << "max: ";
  
cin >> max;

cout << "size: ";
  
cin >> size;

int *tab;
tab = new int [size];

cout << "the numbers are: " << endl;
  
for (int i = 0; i < size; i++)
    
    {
      
tab[i] = rand () % ((max - min) + 1) + min;
  
} 
for (int i = 0; i < size; i++)
    
    {
cout << tab[i] << " ";
    
} 
for(;;){
int wybor;
  
cout << endl << "1. ascending" << endl << "2. descending" << endl
    << "Twoj wybor: ";
  
cin >> wybor;
  
switch (wybor)
    
    {
    
case 1:
      
      {
	
int temp;
	
for (int i2 = 0; i2 <= size - 1; i2++)
	  
	  {
	    
for (int j = 0; j < size; j++)
	      
	      {
		
 
if (tab[j] > tab[j + 1])
		  
		  {
		    
temp = tab[j];
		    
tab[j] = tab[j + 1];
		    
tab[j + 1] = temp;
		  
}
	      
}
	  
}
	
for (int i3 = 0; i3 < size; i3++)
	  
	  {
	    
cout << tab[i3] << " ";
	  
      
}
      
 
 
break;
    
}

case 2:
  
  {
int temp;
	
for (int i2 = 0; i2 <= size - 1; i2++)
	  
	  {
	    
for (int j = 0; j < size; j++)
	      
	      {
		
 
if (tab[j] < tab[j + 1])
		  
		  {
		    
temp = tab[j];
		    
tab[j] = tab[j + 1];
		    
tab[j + 1] = temp;
		  
}
	      
}
	  
}
	
for (int i3 = 0; i3 < size; i3++)
	  
	 
	  {
	    
cout << tab[i3] << " ";
	  
      
}
      
 
 
break;

}
}
}
}
Your arrays WILL be accessed out of bounds on lines 72 and 117, because they will be trying to access tab[size]. Try
for (int j = 0; j < size - 1; j++)
(though the rest of your sorting routine is rather inefficient).

I don't know if that alone will solve your problem, but I think you should reformat your code with proper indentation before much else. It is very hard to read. It's more reliable on multiple platforms if you use spaces rather than tabs for indentation.
Last edited on
Topic archived. No new replies allowed.