-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathc.cpp
114 lines (67 loc) · 2.1 KB
/
c.cpp
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include <iostream>
using namespace std;
// copy the swap function of lab10a
void mySwap(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
// copy the smallest function of lab10b
int smallest(int a[], int left, int right) {
// parameter a[] is the array to be searched
// parameter left is the left index
// parameter right is the right index
// the function returns the index, where a[index] is the
// smallest value in a[left..right]
if (left > right || left < 0 || right < 0) {
return -1;
}
// declare an integer variable called index and initialize it to left
int index = left;
for(int i=left;i<=right;i++)
{
if(a[index] > a[i])
index = i;
}
// a loop to iterate each index from left to right and if variable i
// is used in the iteration we have
// if (a[index] > a[i]) index takes the value of i
// return the value of index
return index;
}
int sorting(int a[], int left, int right) {
// parameter a[] is the array to be sorted
// parameter left is the left index
// parameter right is the right index
// the function returns the index i, where a[i] is the
// smallest value in a[left..right]
if (left > right || left < 0 || right < 0)
return 1;
int index = left;
for(int i=left;i<=right;i++)
{
mySwap(a[i],a[smallest(a,i,right)]);
}
// use a loop to iterate each index from left to right
// and let i be the variable in the iteration
// interchange the values of a[i] and a[ smallest(a, i, right) ]
return 0; //for success
}
// Program to test sorting function
//-----------------------------------------
int main()
{
int a[] = {9,1,5,7,4,2,6,0,8,3};
// test case one
sorting(a, 1, 5);
cout << " The value in A[1..5] is sorted nondecreasingly\n";
for (int i = 0; i<10; i++)
cout << "a[" << i << "] = " << a[i] << endl;
// test case two
sorting(a, 0, 9);
cout << " The value in A[0..9] is sorted nondecreasingly\n";
for (int i = 0; i<10; i++)
cout << "a[" << i << "] = " << a[i] << endl;
return 0;
}