您的位置:首页 > 编程语言 > Java开发

java基础复习-数组排序

2017-08-04 09:37 405 查看
冒泡排序和选择排序

package array;

public class TestArraySort {

/**
* @Title: main
* @Description: TODO(数组的排序)
* @param @param args 设定文件
* @return void 返回类型
* @throws
*/
public static void main(String[] args) {
int arr[]={ 29, 69, 80, 57, 13 };
System.out.println("排序前:");
printArray(arr);
System.out.println("排序后:");
//bubbleSort(arr);
selectSort(arr);
printArray(arr);

}
/**
*
* @Title: bubbleSort
* @Description: TODO(冒泡排序)
* @param @param arr 设定文件
* @return void 返回类型
* @throws
*/
public static void bubbleSort(int[] arr){
for(int i =0; i<arr.length-1; i++){//比较次数是数组长度减一
for(int j=0; j<arr.length-i-1; j++){
if(arr[j]>arr[j+1]){
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}

}
/**
*
* @Title: selectSort
* @Description: TODO(选择排序)
* @param @param arr 设定文件
* @return void 返回类型
* @throws
*/
public static void selectSort(int arr[]){
for(int x=0; x<arr.length-1; x++){
for(int y=x+1; y<arr.length; y++){
if(arr[y] <arr[x]){
int temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;
}
}
}
}
public static void printArray(int []arr){
System.out.print("[");
for(int i=0; i<arr.length; i++){
if(i==arr.length-1){
System.out.print(arr[i]);
}else {
System.out.print(arr[i]+",");
}
}
System.out.println("]");
}

}


把字符串中的字符进行排序
package array;

public class ArraySort {

/**
* @Title: main
* @Description: TODO(把字符串中的字符进行排序)
* @param @param args 设定文件
* @return void 返回类型
* @throws
*/
public static void main(String[] args) {
String s = "asafasfalos";
char[] chs = s.toCharArray();
bubbleSort(chs);
String result = String.valueOf(chs);
System.out.println(result);

}

/**
*
* @Title: bubbleSort
* @Description: TODO(冒泡排序)
* @param @param arr 设定文件
* @return void 返回类型
* @throws
*/
public static void bubbleSort(char[] arr){
for(int i =0; i<arr.length-1; i++){//比较次数是数组长度减一
for(int j=0; j<arr.length-i-1; j++){
if(arr[j]>arr[j+1]){
char temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: