1. 程式人生 > >選擇排序及選擇排序的優化

選擇排序及選擇排序的優化

length 位數 stat 再次 void ray pan static sum

package com.Summer_0421.cn;

import java.util.Arrays;

/**
 * @author Summer
 * 選擇排序
 * 通過記錄下標值,優化選擇排序
 */
public class Test06 {

    public static void main(String[] args) {
        int[] array = {18, 34, 79, 62, 59, 15, 39, 75, 62, 10};
        System.out.println(Arrays.toString(array));
        sort(array);
//選擇排序 System.out.println(Arrays.toString(array)); int[] array1 = {18, 34, 79, 62, 59, 15, 39, 75, 62, 10}; sort1(array1);//選擇排序優化 System.out.println(Arrays.toString(array)); } private static void sort1(int[] a) { int count = 0;//外循環次數 int
count1 = 0;//內循環次數 int count2 = 0;//內循環次數 int index = 0; //記錄下標 int temp; //中間量,第三變量的交換 for (int i = 0; i < a.length-1; i++) { count++; index = i;//將下標值記錄下來 for (int j = i+1; j < a.length; j++) { count1++;
if (a[index]>a[j]) { //記錄當前小的下標 index = j; } } if (index!=i) {//如果最小值的索引與最小值相對應,則不用再次交換 count2++; temp = a[i]; a[i] = a[index]; a[index] = temp; } } System.out.println("外循環次數"+count); System.out.println("內循環次數"+count1); System.out.println("交換次數"+count2); } private static void sort(int [] a) { int count = 0;//外循環次數 int count1 = 0;//內循環次數 int count2 = 0; //交換次數 for (int i = 0; i < a.length-1; i++) {//代表數組中數值位數的下標值,最後一個數字不用比較,所以-1,外循環執行一次,內循環執行一輪 count++; for (int j = i+1; j < a.length; j++) {//第一次循環時,內循環遍歷除第一個數以外的全部數字,以此類推,每次都減少一個數字,並且執行一輪 count1++; //第三變量交換 int temp; if (a[j]<a[i] ) { count2++; temp = a[j]; a[j] = a[i]; a[i] = temp; } } } System.out.println("外循環次數"+count); System.out.println("內循環次數"+count1); System.out.println("交換次數"+count2); } }

選擇排序及選擇排序的優化