选择排序代码java 选择排序代码讲解( 三 )


hasError = true;
break;
}
}
}
}
/**
* Start sort the string containing numbers waited for sort
*/
public void startSort() {
if (numString != null)
if (numString trim() length() != ) {
getDoubleFromString();
startStraightSelectionSort();
setResults();
} else {
setErrorMessage( Please input numbers );
hasError = true;
}
}
/**
* Set the results to the results group
*/
public void setResults() {
if (!hasError) {
String resString = new String();
for (int i = ; inumList size(); i++)
if (i != numList size() )
resString = resString + numList get(i) + ;
else
// If be the last string
resString = resString + numList get(i);
resText setText(resString);
// Clear errorLabel
errorLabel setText( );
}
}
/**
* Sort the numbers using Straight selection Sort algorithm
*/
public void startStraightSelectionSort() {
int minPosition = ;
for (int j = ; jnumList size() ; j++) {
minPosition = j;
for (int i = j + ; inumList size(); i++) {
if (numList get(i)numList get(minPosition)) {
minPosition = i;
}
}
if (minPosition != j) {
// Exchange the minimum with the first number of the numbers
// waited for sort
double temp = numList get(j);
numList set(j numList get(minPosition));
numList set(minPosition temp);
}
}
}
/**
* Set the error message on the error Label
*
* @param errorString
*The string used for set on the errorLabel
*/
public void setErrorMessage(String errorString) {
errorLabel setText(errorString);
// Clear the text of results
resText setText( );
hasError = true;
}
}
Black box Test Case:
)All numbers are zero:
Java几种简单的排序源代码给你介绍4种排序方法及源码,供参考
1.冒泡排序
主要思路: 从前往后依次交换两个相邻的元素,大的交换到后面,这样每次大的数据就到后面 , 每一次遍历,最大的数据到达最后面 , 时间复杂度是O(n^2) 。
public static void bubbleSort(int[] arr){
for(int i =0; iarr.length - 1; i++){
for(int j=0; jarr.length-1; j++){
if(arr[j]arr[j+1]){
arr[j] = arr[j]^arr[j+1];
arr[j+1] = arr[j]^arr[j+1];
arr[j] = arr[j]^arr[j+1];
}
}
}
}
2.选择排序
主要思路:每次遍历序列 , 从中选取最小的元素放到最前面,n次选择后,前面就都是最小元素的排列了,时间复杂度是O(n^2) 。
public static void selectSort(int[] arr){
for(int i = 0; i arr.length -1; i++){
for(int j = i+1; jarr.length; j++){
if(arr[j]arr[i]){
arr[j] = arr[j]^arr[i];
arr[i] = arr[j]^arr[i];
arr[j] = arr[j]^arr[i];
}
}
}
}
3.插入排序
主要思路:使用了两层嵌套循环,逐个处理待排序的记录 。每个记录与前面已经排好序的记录序列进行比较,并将其插入到合适的位置,时间复杂度是O(n^2) 。
public static void insertionSort(int[] arr){
int j;
for(int p = 1; parr.length; p++){
int temp = arr[p];//保存要插入的数据
//将无序中的数和前面有序的数据相比,将比它大的数,向后移动
for(j=p; j0temp arr[j-1]; j--){
arr[j] = arr[j-1];
}
//正确的位置设置成保存的数据
arr[j] = temp;
}
}
4.希尔排序
主要思路:用步长分组,每个分组进行插入排序,再慢慢减小步长,当步长为1的时候完成一次插入排序,希尔排序的时间复杂度是:O(nlogn)~O(n2),平均时间复杂度大致是O(n^1.5)

推荐阅读