#include <stdio.h> const int N=5; int binarySearch(int *x, int n, int item); int main() { int a[N]={1,3,9,16,21}; int i,index, key; printf("數組a中的數據:\n"); for(i=0;i<N;i++) printf("%d ",a[i]); printf("\n"); printf("輸入待查找的數據項: "); scanf("%d", &key); // 調用函數binarySearch()在數組a中查找指定數據項item,并返回查找結果 // 補足代碼① // ××× index=binarySearch(a,N,key); if(index>=0) printf("%d在數組中,下標為%d\n", key, index); else printf("%d不在數組中\n", key); return 0; } //函數功能描述: //使用二分查找算法在x指向的數據項開始的n個數據中,查找item // 如果找到,返回其位置 // 如果沒找到,返回-1 int binarySearch(int *x, int n, int item) { int low, high, mid; low = 0; high = n-1; while(low <= high) { mid = (low+high)/2; if (item == *(x+mid)) return mid; else if(item < *(x+mid)) high = mid - 1; else low = mid + 1; } return -1; }
2選擇法排序
選擇法排序的算法思想 選出n個數中最小的數與第1個數交換; 選出次小的數與第2個交換; 以此類推,...; 選出次大的數與第n-1個數交換。
#include <stdio.h> #include <string.h> void selectSort(char str[][20], int n ); // 函數聲明,形參str是二維數組名 int main() { char name[][20] = {"John", "Alex", "Joseph", "Candy", "Geoge"}; int i; printf("輸出初始名單:\n"); for(i=0; i<5; i++) printf("%s\n", name[i]); selectSort(name, 5); // 調用選擇法對name數組中的字符串排序 printf("按字典序輸出名單:\n"); for(i=0; i<5; i++) printf("%s\n", name[i]); return 0; } // 函數定義 // 函數功能描述:使用選擇法對二維數組str中的n個字符串按字典序排序 void selectSort(char str[][20], int n) { int i, j, k; char temp[20]; for(i=0; i<n-1; i++) { k = i; for(j=i+1; j<n; j++) if (strcmp(str[j] , str[k])<0 ) k = j; if(k != i) { strcpy(temp ,str[i]); strcpy(str[i] ,str[k]); strcpy(str[k] , temp); } } }

#include <stdio.h> const int N=5; int binarySearch(int x[], int n, int item); int main() { int a[N]={61,24,5,4,85}; int i,index, key; printf("數組a中的數據:\n"); for(i=0;i<N;i++) printf("%d ",a[i]); printf("\n"); printf("輸入待查找的數據項: "); scanf("%d", &key); // 調用函數binarySearch()在數組a中查找指定數據項item,并返回查找結果給index // 補足代碼① // ××× index=binarySearch(a,N,key); if(index>=0) printf("%d在數組中,下標為%d\n", key, index); else printf("%d不在數組中\n", key); return 0; } //函數功能描述: //使用二分查找算法在數組x中查找特定值item,數組x大小為n // 如果找到,返回其下標 // 如果沒找到,返回-1 int binarySearch(int x[], int n, int item) { int low, high, mid; low = 0; high = n-1; while(low <= high) { mid = (low+high)/2; if (item == x[mid]) return mid; else if(item<x[mid]) high = mid - 1; else low = mid + 1; } return -1; }

C語言對我來說學起來還是很難,我會努力學的。
浙公網安備 33010602011771號