-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstoogesort.cpp
More file actions
74 lines (58 loc) · 1.46 KB
/
stoogesort.cpp
File metadata and controls
74 lines (58 loc) · 1.46 KB
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
// C++ code to implement stooge sort
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
vector<int> arr;
ifstream infile("data.txt");
// Function to implement stooge sort
void stoogesort(vector<int> &arr, int first, int last)
{
// If first element is smaller than last, swap them
if (arr[first] > arr[last])
swap(arr[first], arr[last]);
// If there are more than 2 elements in the array
if (last - first + 1 > 2)
{
int t = (last - first + 1) / 3;
// Recursively sort first 2/3 elements
stoogesort(arr, first, last - t);
// Recursively sort last 2/3 elements
stoogesort(arr, first + t, last);
// Recursively sort first 2/3 elements again to confirm
stoogesort(arr, first, last - t);
}
}
void printFinal(vector<int> &arr, int n)
{
ofstream myfile;
myfile.open("stooge.out");
for (int i = 0; i < n; i++)
{
// Storing the sorted array
myfile << arr[i] << " ";
}
myfile.close();
}
// Main Code which passes the
int main()
{
if (!infile)
{
cout << "File does not exist" << endl;
}
ifstream file("data.txt");
int data;
while (file >> data)
{
arr.push_back(data);
}
int n = arr[0];
arr.erase(arr.begin());
// Calling Stooge Sort function to sort
// the array
stoogesort(arr, 0, n - 1);
// Print the Output in stooge.out
printFinal(arr, n);
return 0;
}