173 lines
4.1 KiB
C++

#include <iostream>
#include <ctime>
using namespace std;
void swap(int *a, int *b) {
int t = *a;
*a = *b;
*b = t;
}
int partition(int A[], int low, int high) {
int m = (low + high) / 2;
swap(&A[low], &A[m]);
int w = A[low];
int i = low;
int j = high;
while (j > i) {
while (A[j] >= w && j > low) j = j - 1;
while (A[i] <= w && i < high) i = i + 1;
if (i < j) {
swap(&A[i], &A[j]);
}
}
swap(&A[low], &A[j]);
return j;
}
void quickSort(int A[], int low, int high) {
if (low < high) {
int j = partition(A, low, high);
quickSort(A, low, j - 1);
quickSort(A, j + 1, high);
}
}
void bubbleSort(int A[], int length) {
int rep = 0;
for (int i = 0; i < length; i++) {
if (rep == 10000) {
cout << ".";
rep = 0;
}
rep++;
for (int j = 0; j < length - i - 1; j++) {
if (A[j] < A[j + 1]) swap(&A[j], &A[j + 1]);
}
}
cout << "\n";
}
void fillArray(int A[], int length) {
for (int i = 0; i < length; i++) {
A[i] = rand();
}
}
void highToLow(int A[], int length) {
int base = length;
for (int i = 0; i < length; i++) {
A[i] = base;
base--;
}
}
void print(int A[], int length) {
for (int i = 0; i < length; i++) {
cout << A[i] << " ";
}
cout << endl;
}
bool check(const int A[], int length) {
for (int i = 0; i < length - 1; i++) {
if (A[i] > A[i + 1]) {
return false;
}
}
return true;
}
void menu() {
cout << "1 ... Generate random sequence \n"
"2 ... Generate sorted rising sequence \n"
"3 ... Generate sorted falling sequence \n"
"4 ... Print sequence \n"
"5 ... quickSort sequence \n"
"6 ... bobbleSort sequence \n"
"7 ... Check sequence \n"
"0 ... End \n \n"
"Your choice: ";
}
int main() {
int length;
// int A[length];
int *A = NULL;
int low = 0;
int high = length - 1;
srand(time(nullptr));
bool running = true;
int selection;
clock_t start, finish;
double duration;
do {
menu();
cin >> selection;
cout << endl;
switch (selection) {
case 1:
cout << "dolzina";
cin >> length;
high = length - 1;
A = new int[length];
fillArray(A, length);
break;
case 2:
cout << "dolzina";
cin >> length;
high = length - 1;
A = new int[length];
fillArray(A, length);
quickSort(A, low, high);
break;
case 3:
cout << "dolzina";
cin >> length;
high = length - 1;
A = new int[length];
highToLow(A, length);
break;
case 4:
print(A, length);
break;
case 5:
start = clock();
quickSort(A, low, high);
finish = clock();
duration = (double) (finish - start) / CLOCKS_PER_SEC;
cout << "Time to sort " << duration << "\n";
break;
case 6:
start = clock();
bubbleSort(A, length);
finish = clock();
duration = (double) (finish - start) / CLOCKS_PER_SEC;
cout << "Time to sort " << duration << "\n";
break;
case 7:
if (check(A, length)) {
cout << "Sequence is sorted \n";
} else {
cout << "Sequence isn't sorted \n";
}
break;
case 0:
running = false;
break;
default:
cout << "Wrong selection!" << endl;
break;
}
cout << endl;
} while (running);
delete[]A;
return 0;
}