// bubble sort double a[5]={34,12,56,4,7}; int len = sizeof(a) / sizeof(double);
//output all numbers cout << "before sorted by bubbleSort:" <<endl; for (int i=0;i<len;i++) { cout << a[i]<<"\t"; } cout << endl;
//start to sort the array for (int i=0;i<len-1;i++) { for(int j=0;j<len -i -1;j++) { if(a[j]>a[j+1]) { double t = 0; t = a[j]; a[j] = a[j+1]; a[j+1] = t; } } cout << "This is at NO." << i << "time: "; for(int i=0;i<len;i++) cout << a[i] << "\t"; cout << endl;
}
//output after sorted cout << "after sorted by bubbleSort:"<<endl; for (int i=0;i<len;i++) { cout << a[i]<<"\t"; } cout << endl;
//selectsort double b[5]={34,12,56,4,7};
cout << "before sorted by selectSort:" << endl; for (int i=0;i<len;i++) { cout << b[i]<< "\t"; } cout << endl; //start to selectSort for(int i=0;i<len-1;i++) { int minIndex = i;//pretend the first number of the array be the min number.and record the index cout << "ending->minIndex=" << minIndex << endl; for (int j=i+1;j<len;j++) { if(b[minIndex]>b[j]) { minIndex = j; } } if(minIndex != i) { double t = 0; t = b[i]; b[i] = b[minIndex]; b[minIndex] = t;
} //print the detail cout << "This is at NO." << i << "time: "; for(int i=0;i<len;i++) cout << setw(4)<<b[i] ; cout << " "<< "ending->minIndex=" << minIndex << endl;
} cout << "after sorted by selectSort:" << endl; for (int i=0;i<len;i++) { cout << b[i]<<"\t"; } cout << endl;
publicclassBubble{ publicstaticvoidmain(String[] args){ int[] b = {3, 1, 4, 2,89,76,35}; for (int i = 0; i < b.length; i++) { System.out.print(b[i]); } System.out.println(); int[] c = bubble(b); for (int i = 0; i < c.length; i++) { System.out.print(c[i] + "\t"); } System.out.println(); int[] d = select(b); for (int i = 0; i < d.length; i++) { System.out.print(d[i] + "\t"); }
}
publicstaticint[] bubble(int[] a) { for (int i = 0; i < a.length - 1; i++) { for (int j = 0; j < a.length - 1 - i; j++) { if (a[j+1] < a[j]) { int temp = a[j+1]; a[j+1] = a[j]; a[j] = temp; } } } return a; }
publicstaticint[] select(int[] a){ int maxIndex = 0; int i,j; for (i = 0; i < a.length; i++) { for (j=0; j< a.length -1 ;j++){ if (a[maxIndex] < a[j]){ maxIndex = j; } } } if(maxIndex != i){ return a; } returnnull;