Problem with sorting using rand()

Hello,i'm sorry to bother you with simple question like this but i'm learning c++
and i can't seem to figure out why am i not getting a sorted version.
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <cstdlib>


using namespace std;

int main(){


int chuska[200];
int temp;
bool done=false;

 for (int i=0;i<100;i++)
{
chuska[i]=rand();
}
for (int i=0;i<100;i++)
{
cout<< i+1 << "." << chuska[i] << endl;
}
cout << "===========sorted==array=========" << endl;

while(!done)
     {
        done=true;
for (int g=0;g<100;g++)
{
 if(chuska[g]>chuska[g+1])
 {
     temp=chuska[g];
     chuska[g]=chuska[g+1];
     chuska[g+1]=temp;
      done=false;
      }
      }
      }

for (int i=0;i<100;i++)
{
 cout << chuska[i] << endl;
}
return 0;
}
You forgot to initialize the rand() with srand(time(NULL)). There are other errors, too.
Your logic must be the Selection Sort logic: search for the minimum element and swap it with the instance

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
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <algorithm>

//selection sorting algorithm
//THAT'S THE WORST SORTING ALGORITHM
void selection_sort(int number[100], int instance = 0)
{
    for(int i = 0; i < 100; i++)
        std::swap(number[i], *std::min_element(number + i, number + 100));
}

int main()
{
    srand(time(NULL)); //Initialize rand();
    int array[100] = {0}; //Initialize the array of random numbers
    for(int i = 0; i < 100; i++)
        //Insert random number
        array[i] = rand();
    for(auto a : array) std::cout << a << std::endl;
    selection_sort(array);
    std::cout << "Entire array: (sorted)\n";
    for(int i = 0; i < 100; i++) std::cout << array[i] << std::endl;
}
Thanks!
Topic archived. No new replies allowed.