1. 程式人生 > >用Java實現的選擇排序和冒泡排序

用Java實現的選擇排序和冒泡排序

auth main sta -i str public java index 選擇

選擇排序

package cn.hxd.sort;
/**
 * 選擇排序
 * @author Administrator
 *
 */
public class SelectionSort {
	public static double[] selectionSort(double[] list) {
		for(int i=0;i<list.length-1;i++) {
			double currentMin = list[i];
			int currentMinIndex = i;
			//從list[i...list.length-1]中選出最小值
			for(int j=i+1;j<list.length;j++) {
				if(currentMin > list[j]) {
					currentMin = list[j];
					currentMinIndex = j;
				}
			}
			//將最小值與list[i]交換
			if(currentMinIndex != i) {
				list[currentMinIndex] = list[i];
				list[i] = currentMin;
			}
		}
		return list;
	}
	
	public static void main(String[] args) {
		double[] list = {1,3,2,7,4,5,8,6,9,2};
		selectionSort(list);
		for(int i=0;i<list.length;i++) {
			System.out.print(list[i]+" ");
		}
	}
}

冒泡排序:

package cn.hxd.sorttest;
/**
 * 冒泡排序
 * @author Administrator
 *
 */
public class BubbleSort {
	
	public static int[] bubbleSort(int[] list) {
		for(int i=0;i<list.length-1;i++) {
			for(int j=0;j<list.length-1-i;j++) {
				if(list[j]>list[j+1]) {
					int temp = list[j];
					list[j] = list[j+1];
					list[j+1] = temp;
				}
			}
		}
		return list;
	}
	public static void main(String[] args) {
		int[] list = {3,7,5,9,2,7,6,4};
		bubbleSort(list);
		for(int i=0;i<list.length;i++) {
			System.out.print(list[i]+",");
		}
	}
}

  

用Java實現的選擇排序和冒泡排序