In: Computer Science
I am trying to sort a group of 10 randomly generated numbers from least to greatest in c++.
Right now, my code isn't working and is giving odd results. There is extra unecessary code since I was trying to find out what wasn't working.
In this example I am trying to use the bubble sort method but bucket sort would also be okay. Please keep the format the same and don't use any other functions not currently in the code, thanks.
void arraysort()
{
const int N = 10;
int x[N];
for(int i = 0; i < N; i++)
{
x[i] = 1 + gRandom-> Rndm() * 10;
cout<<x[i]<<" ";
}
cout<<endl;
int temp;
for(int i = 0; i < N-1; i++)
{
if(x[i] > x[i+1]){
cout<<x[i]<<", "<<x[i+1]<<endl;
temp = x[i];
x[i] = x[i+1];
x[i+1] = temp;
continue;
}
if(x[i] < x[i+1]){
cout<<"here"<<", "<<x[i]<<", "<<x[i+1]<<endl;
continue;
}
}
cout<<endl<<endl<<endl;
for(int i = 0; i < N; i++)
{
cout << x[i] << " ";
}
#include<iostream>
#include <stdlib.h>
#include<time.h>
#include <cstdlib>
using namespace std;
void arraysort()
{
const int N = 10;
srand(time(NULL));
int x[N];
cout<<"Before sorting: ";
for(int i = 0; i < N; i++)
{
x[i] = 1 + rand() * 10;
cout<<x[i]<<" ";
}
cout<<endl;
cout<<"After sorting: ";
int temp;
for(int i=0; i<N; i++)
{
for(int j=i+1; j<N; j++)
{
//If there is a smaller element found on right of the xay then swap
it.
if(x[j] < x[i])
{
int temp = x[i];
x[i] = x[j];
x[j] = temp;
}
}
}
cout<<endl;
for(int i = 0; i < N; i++)
{
cout << x[i] << " ";
}
cout<<endl;
}
int main()
{
arraysort();
}