2. Selection Sort演算法
3. main函數的輸入與輸出
#include <stdio.h> #include <stdlib.h> #include <math.h> #define MAX_SIZE 100 void sort(int list[], int n); int binsearch(int list[], int n, int left, int right); int main(int argc, char *argv[]) { int i, n; int searchnum, left, right, pos; int list[MAX_SIZE]; printf("Enter the number of numbers to generate: "); scanf("%d", &n); if ((n < 1) || (n > MAX_SIZE)) { fprintf(stderr, "Improper value of n\n"); exit(1); } printf("hello\n"); for (i = 0; i < n; i++) { list[i] = rand() % 1000; printf("%d ", list[i]); } printf("\n"); sort(list, n); for (i = 0; i < n; i++) printf("%d ", list[i]); printf("\n"); printf("Enter the numbfer you want to search: "); scanf("%d", &searchnum); left = 0; right = n - 1; pos = binsearch(list, searchnum, left, right); if (pos == -1) printf("not found\n"); else printf("found pos: %d\n", pos); return 0; }
#define SWAP(x, y, t) ((t) = (x), (x) = (y), (y) = (t)) void sort(int list[], int n) { int i, j, min, temp; for (i = 0; i < n-1; i++) { min = i; for (j = i+1; j < n; j++) if (list[min] > list[j]) min = j; SWAP(list[i], list[min], temp); } }
沒有留言:
張貼留言