0
点赞
收藏
分享

微信扫一扫

**选择排序 SelectSort 文章内含源码**


选择排序:在一串数组中找到一个最小值直接放到第一位(索引为0的位置)

package cn.Text;

public class SelectionSort {
public static void SelectSort(int[] arr) {
//先写边界条件
if (arr==null || arr.length<2){
return;
}
//0~n-1 1~n-1 2~n-1 ...
for (int i = 0; i < arr.length; i++) {
//i~n-1
int MINValueIndex=i;
for (int j = i+1; j < arr.length; j++) {
MINValueIndex=arr[j]<arr[MINValueIndex]?j:MINValueIndex;
}
Swap(arr,i,MINValueIndex);
}
}
public static void Swap(int [] arr ,int i,int j){
int tmp=arr[j];
arr[j]=arr[i];
arr[i]=tmp;

}
public static void PrintArray(int [] arr){
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]+" ");
}
System.out.println();
}
public static void main(String[] args) {
int[] arr={5,9,13,22,4,56,3};
PrintArray(arr);
SelectSort(arr);
PrintArray(arr);
}
}

**选择排序 SelectSort 文章内含源码**_边界条件



举报

相关推荐

0 条评论