package order;
/*
* 冒泡排序
*/
public class Bubble {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = {26,30,27,40,35,18};
System.out.println("排序前的顺序为:");
printArr(arr);
System.out.println("排序后的顺序为:");
bubbleSort(arr);
printArr(arr);
}
//数组的排序
public static void bubbleSort(int[] arr){
int temp;
for(int i=0;i<arr.length-1;i++){
for(int j=0;j<arr.length-1-i;j++){
if(arr[j]>arr[j+1]){
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
//数组的遍历
public static void printArr(int[] arr){
System.out.print("[");
for(int i=0;i<arr.length;i++){
if(i==arr.length-1){
System.out.print(arr[i]+"]"+"\n");
}else{
System.out.print(arr[i]+",");
}
}
}
}
package order;
/*
* 选择排序
*/
public class Select {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = {26,30,27,40,35,18};
System.out.println("排序前的顺序为:");
printArr(arr);
System.out.println("排序后的顺序为:");
selectSort(arr);
printArr(arr);
}
public static void selectSort(int[] arr){
for(int i=0;i<arr.length-1;i++){
for(int j=i+1;j<arr.length;j++){
if(arr[j]<arr[i]){
int temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
}
}
//数组的遍历
public static void printArr(int[] arr){
System.out.print("[");
for(int i=0;i<arr.length;i++){
if(i==arr.length-1){
System.out.print(arr[i]+"]"+"\n");
}else{
System.out.print(arr[i]+",");
}
}
}
}
package order;
/*
* 定义一个字符串:s="dbasgc";
* 按字母排序:abcdgs
* 分析:1.把字符串转为字符数组
* 2.把字符数组进行排序(冒泡排序)
* 3.把排序后的数组转换为字符串
*/
public class bubbleTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
//定义一个字符串
String s = "dbasgc";
//把字符串转化为字符数组
char[] ch = s.toCharArray();
System.out.println("排序前的顺序为:");
printArr(ch);
System.out.println("排序后的顺序为:");
bubbleSort(ch);
//把排序后的字符数组转换为字符串
//String result = String.valueOf(ch);
String result = s.toString();//这两种方法均可
printArr(ch);
}
//冒泡排序
public static void bubbleSort(char[] ch){
for(int i=0;i<ch.length-1;i++){
for(int j=0;j<ch.length-1-i;j++){
if(ch[j]>ch[j+1]){
char temp = ch[j];
ch[j] = ch[j+1];
ch[j+1] = temp;
}
}
}
}
public static void printArr(char[] ch){
for(int i=0;i<ch.length;i++){
if(i==ch.length-1){
System.out.print(ch[i]+"\n");
}else{
System.out.print(ch[i]+",");
}
}
}
}