1 // Example program 2 #include <iostream> 3 #include <string> 4 #include<algorithm> 5 6 using namespace std; 7 void select(int *L,int n) 8 { 9 if(n <= 0 ) 10 return; 11 int temp = 0 ; 12 for(int i =0 ;i < n ;i++) 13 { 14 temp = L[i]; 15 for(int j = i+1 ; j < n; j++) 16 { 17 if(L[j] < temp) 18 temp = L[j]; 19 } 20 swap(temp,L[i]); 21 } 22 } 23 24 25 int main() 26 { 27 28 int a[5] = {1,2,6,3,4}; 29 select(a,5); 30 for(int i =0 ;i<5; i++) 31 { 32 printf("%d ",a[i]); 33 } 34 }
我的这种做法有很大的漏洞,当运行到6的时候只是顶替了,没有交换,所以会造成结果不对。
void select(int *L,int n) { if(n <= 0 ) return; int temp = 0 ; int min = 0; for(int i =0 ;i < n ;i++) { temp = L[i]; min = i; for(int j = i+1 ; j < n; j++) //作用:在for中实现关键字之后的元素进行比较,选的最小值 { if(L[j] < temp) { temp = L[j]; // 这两句缺一不可 min = j; } } swap(L[min],L[i]); } }
但是上面写的比较冗余 没有标准简便。
// Example program #include <iostream> #include <string> #include<algorithm> using namespace std; void select(int *L,int n) { if(n <= 0 ) return; // int temp = 0 ; int min = 0; for(int i =0 ;i < n ;i++) { // temp = L[i]; min = i; for(int j = i+1 ; j < n; j++) { if(L[j] < L[min]) { //temp = L[j]; min = j; //这里比较出最小的来,要更新上去。要选出后序序列中最小的呢 } } if(i != min ) swap(L[min],L[i]); } } int main() { int a[5] = {1,2,6,3,4}; select(a,5); for(int i =0 ;i<5; i++) { printf("%d ",a[i]); } }
在数组比较的时候,要注意是否转换过来了。