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
| #include <iostream> #include<ctime> #include<cstdlib> using namespace std; int selectMinKey(int* arr, int m, int length); void selectSortToMin(int* arr, int length); void selectSortToMax(int* arr, int length); void swap(int& a, int& b); void output(int* arr, int n); void inputRandCount(int *arr, int n); void dynamicApplication(int*& arr, int &n); int main(int argc,char *argv[]) { int n = 0,*arr=NULL; dynamicApplication(arr, n); inputRandCount(arr, n); cout << "原先的数组为:" << endl; output(arr, n); selectSortToMin(arr, n); cout << "排序后的数组为:"<<endl; output(arr, n); free(arr); }
int selectMinKey(int* arr, int m, int length) { int min = m; for (int i = m + 1; i < length; i++) { if (arr[i] < arr[min]) { min = i; } } return min; }
int selectMaxKey(int* arr, int m, int length) { int max = m; for (int i = m + 1; i < length; i++) { if (arr[i] > arr[max]) { max = i; } } return max; }
void selectSortToMin(int* arr, int length) { int min = 0; for (int i = 0; i < length; i++) { min = selectMinKey(arr, i, length); swap(arr[i], arr[min]); } }
void selectSortToMax(int* arr, int length) { int max = 0; for (int i = 0; i < length; i++) { max = selectMaxKey(arr, i, length); swap(arr[i], arr[max]); } }
void swap(int& a, int& b) { int temp = 0; temp = a; a = b; b = temp; }
void output(int* arr,int n) { for (int i = 0; i < n; i++) { cout << *(arr + i) << " "; } cout << endl; }
void inputRandCount(int *arr, int n) {
srand((unsigned)time(NULL)); for (int i = 0; i < n; i++) { *(arr + i) = rand() % 1000; } }
void dynamicApplication(int*& arr, int &n) { cout << "请输入数组的元素个数n:" << endl; cin >> n; arr = (int*)malloc(sizeof(int) * n); if (NULL == arr) { perror("malloc"); exit(0); } }
|