排序:選擇排序

算法步驟java

1)首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置算法

2)再從剩餘未排序元素中繼續尋找最小(大)元素,而後放到已排序序列的末尾。測試

3)重複第二步,直到全部元素均排序完畢。code

選擇排序(Java)排序

public static int[] selectionSort(int[] elements) {
	int temp = 0;
	if(null == elements || 1 >= elements.length) {
		// do nothing
	} else {
		System.out.println("elements="+Arrays.toString(elements));
		System.out.println("------------------------------------------------");
		for(int i=0;i<elements.length-1;i++) {
			for(int j=i+1;j<elements.length;j++) {
				if(elements[i] > elements[j]) {
					temp = elements[i];
					elements[i] = elements[j];
					elements[j] = temp;
				}
			}
			System.out.println("elements="+Arrays.toString(elements));
			System.out.println("------------------------------------------------");
		}
	}
	return elements;
}

測試代碼:element

public static void main(String[] args) {
	int[] array = {82 ,31 ,29 ,71, 72, 42, 64, 5, 110};
	selectionSort(array);
}

排序結果:io

elements=[82, 31, 29, 71, 72, 42, 64, 5, 110]
------------------------------------------------
elements=[5, 82, 31, 71, 72, 42, 64, 29, 110]
------------------------------------------------
elements=[5, 29, 82, 71, 72, 42, 64, 31, 110]
------------------------------------------------
elements=[5, 29, 31, 82, 72, 71, 64, 42, 110]
------------------------------------------------
elements=[5, 29, 31, 42, 82, 72, 71, 64, 110]
------------------------------------------------
elements=[5, 29, 31, 42, 64, 82, 72, 71, 110]
------------------------------------------------
elements=[5, 29, 31, 42, 64, 71, 82, 72, 110]
------------------------------------------------
elements=[5, 29, 31, 42, 64, 71, 72, 82, 110]
------------------------------------------------
elements=[5, 29, 31, 42, 64, 71, 72, 82, 110]
------------------------------------------------
相關文章
相關標籤/搜索