目錄
-
排序
1.冒泡排序
原理
實現
void BubbleSort1(int* num,int n) { int temp; for(int i=0;i<n-1;i++) { for(int j=0;j<n-1-i;j++) { if(num[j]<num[j+1]) { temp=num[j]; num[j]=num[j+1]; num[j+1]=temp; } } } }
void BubbleSort2(int* num,int n) { int temp; int flag=1;//無序標誌位 for(int i=0;i<n-1&&flag==1;i++) { flag=0; for(int j=0;j<n-1-i;j++) { if(num[j]>num[j+1]) { temp=num[j]; num[j]=num[j+1]; num[j+1]=temp; flag=1; } } } }
查找:
1.順序查找
原理:
順序查找就是在關鍵字集合中找出與給定的關鍵字相等的元素。
實現:
#include <iostream> using namespace std; typedef struct student { unsigned int id; char name[10]; int score; }Student; int searchinfo(Student *stu,int num,int id) { for(int i=0;i<num;i++) { if(stu[i].id==id) return i; } return -1; } int main() { Student stu[4]={{1004,"TOM",100}, {1002," LILY",95}, {1001,"ANN",93}, {1003,"luCY",98}}; int address; address=searchinfo(stu,4,1001); std::cout<<"ID: "<<stu[address].id<<std::endl; std::cout<<"name: "<<stu[address].name<<std::endl; std::cout<<"score: "<<stu[address].score<<std::endl; return 0; }
時間複雜度:O(N)
2.折半查找
原理:
實現:
#include<iostream> using namespace std; int binary_search(int num[],int target,int n) { int low=0; int high=n-1; int middle; while(low<=high) { middle=low+(high-low)/2; if(num[middle]==target) { return middle; } if(num[middle]<target) { low=middle+1; } else { high=middle-1; } } } int main() { int num[10]; cout<<"請輸入一個數組: "<<endl; for(int i=0;i<10;i++) { cin>>num[i]; } int target; cout<<"請輸入需要查找的數: "<<endl; cin>>target; int position=binary_search(num,target,10); cout<<"結果爲: "<<num[position]<<" 位置: "<<position<<endl; return 0; }
時間複雜度:O(log2n)