I am a beginner programmer and have written a program that sorts a number of integers of your choosing using bogo sort.
Are there any improvements that could be made to make this code more efficient (ironic, but you get the idea)? Are there any ways to make this code easier to read for someone else?
#include <iostream>
#include <time.h>
using namespace std;
int findModulus(int quotient, int divisor);
int main()
{
cout << "Hello, welcome to the Bogo Sort Algorithm!" << endl;
srand(time(NULL));
//First sections establishes the dimensions of the matrices
int entryNum ;
cout << "Number of values: ";
cin >> entryNum;
int seq[entryNum];
int plchlderSeq[entryNum];
bool seqIsSorted;
int chosenOrder[entryNum];
int chosenOrderPreOp[entryNum];
int numbers[entryNum];
int i,j,k;
cout << "Input the values: ";
for(i=1; i<=entryNum; i++){
cin >> seq[i-1];
}
do{
seqIsSorted = true;
for(i=1; i<=entryNum; i++){
numbers[i-1] = i ;
}
//this section is for randomising the order of (1, ... , entryNum), remove comments to see it in action
for(i=1; i<=entryNum; i++){
chosenOrderPreOp[i-1] = findModulus(rand(),entryNum-i+1);
//cout << chosenOrderPreOp[i-1] << "\n";
chosenOrder[i-1] = numbers[chosenOrderPreOp[i-1]];
//cout << chosenOrder[i-1] << "\n";
for(j = chosenOrderPreOp[i-1]+1 ; j <= entryNum-i ; j++){
numbers[j-1] = numbers[j]; // copy next element left
for(k=1; k<=entryNum; k++){
//cout << numbers[k-1] << " ";
}
//cout << " \n";
}
/*
for(j=1; j<=entryNum-i; j++){
cout << numbers[j-1] << " ";
}*/
//cout << " \n";
}
for(i=1; i<=entryNum; i++){
//cout << chosenOrder[i-1] << " ";
}
//cout << "\n";
for(i=1; i<=entryNum; i++){
plchlderSeq[i-1] = seq[chosenOrder[i-1]-1];
}
for(i=1; i<=entryNum; i++){
seq[i-1] = plchlderSeq[i-1];
}
for(i=1; i<=entryNum-1; i++){
if(seq[i-1] > seq[i]){
seqIsSorted = false;
}
}
for(i=1; i<=entryNum; i++){
//cout << seq[i-1] << " ";
}
if(seqIsSorted){
cout << "\nSequence is sorted \n";
for(i=1; i<=entryNum; i++){
cout << seq[i-1] << " ";
}
} else{
//cout << "\nSequence is not sorted \n";
}
}while(!seqIsSorted);
return 0;
}
int findModulus(int quotient, int divisor){
int result;
do{
result = quotient;
quotient = quotient-divisor;
}while(quotient >= 0);
return result;
}
int seq[entryNum];
with non constexprentryNum
is not valid c++ (that use VLA extension). usestd::vector
instead. \$\endgroup\$bogosort
can simply use std::shuffle andstd::is_sorted
. \$\endgroup\$