实验 5
---恢復內容開始---
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?實驗五
實驗總結和體會
1、二分查找算法
(1)形參是數組,實參是數組名,使用數組元素直接訪問方式實現
// 練習:使用二分查找,在一組有序元素中查找數據項 // 形參是數組,實參是數組名 #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 // 補足代碼① index = binarySearch(a,N,key) ;if(index>=0) printf("%d在數組中,下標為%d\n", key, index);elseprintf("%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;elselow = mid + 1;}return -1;}(2)形參是指針變量,實參是數組名,使用指正變量間接訪問方式實現
// 練習:使用二分查找,在一組有序元素中查找數據項 // 形參是指針變量,實參是數組名 #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);elseprintf("%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;elselow = mid + 1;}return -1; }2、選擇法排序
// 練習:使用選擇法對字符串按字典序排序 #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; strcpy(temp,str[i]); for(j=i+1;j<n;j++)if(strcmp(str[j],str[k])<0)k=j;strcpy(temp,str[j]);if(k!=i){strcpy(temp,str[i]);strcpy(str[i],str[k]);strcpy(str[k],temp); }} }實驗總結和體會
1、做完實驗后,對于指針變量的間接訪問形式有了一定的理解,但有時還是會迷惑,為什么要這樣做。
2、用選擇法對字符串排序的時候,我能懂算法思路,但是把它轉換成代碼還是有些費勁,閱讀代碼倒是沒什么問題,可是如果讓我自己寫的話,我可能寫不完整,因為腦子里還沒有形成一種框架,希望以后在多多練習的過程中能有提高。
3、感覺C語言博大精深,隨時隨地都會新的東西,所以要多多查閱,邊查邊記憶。
?
互評地址:
https://www.cnblogs.com/shauifan/p/10924048.html
https://www.cnblogs.com/1256096713a/p/10925944.html
https://www.cnblogs.com/bu-xiu/p/10925969.html
?
轉載于:https://www.cnblogs.com/lxl720/p/10932414.html
總結
- 上一篇: 16第一章ASP.Net编程基础知识
- 下一篇: cmd与monkey测试