简单排序学习

来源:互联网 发布:linux下安装vmware12 编辑:程序博客网 时间:2024/04/29 14:38

简单排序:

1、选取第一元素作为基准位置,依次跟后面的元素比较,如果后面的元素比这个基准位置的元素小,则互换两个元素的值,一直到和最后一个元素比较完,得出基准位置的元素为最小的元素;

2、选取第二元素作为基准位置,依次跟后面的元素比较,如果后面的元素比这个基准位置的元素小,则互换两个元素的值,一直到和最后一个元素比较完,得出基准位置的元素为第二小的元素;

      ......

3、根据上诉方法操作一直到最后一位获得的将会是按小到大的顺序排好序的数组;

public class SimpleSort {
    
    private static int num=0; //循环次数
    /**
     * 递归简单排序
     * @param forSort
     * @param i
     * @return
     */
    public int[] sort(int[] forSort,int i){
        if(i<forSort.length-1){
            int k = forSort[i];
            for(int j = i+1 ; j<forSort.length ; j++){
                if(forSort[j] < k){
                    forSort[i] = forSort[j];
                    forSort[j] = k;
                    k = forSort[i];
                }
            }
            i++;
            System.out.println("分次结果:"+Arrays.toString(forSort)+",i="+i);
            sort(forSort, i);
        }
        return forSort;
    }
    
    /**
     * 循环简单排序
     * @param forSort
     * @param i
     * @return
     */
    public int[] loopSort(int[] forSort,int i){
        while(i<forSort.length-1){
            int k = forSort[i];
            for(int j = i+1 ; j<forSort.length ; j++){
                if(forSort[j] < k){
                    forSort[i] = forSort[j];
                    forSort[j] = k;
                    k = forSort[i];
                }
                num++;
            }
            i++;
            System.out.println("分次结果:"+Arrays.toString(forSort)+",i="+i);
        }
        return forSort;
    }
    
    public static void main(String[] args) {
        int[] array = {2,5,6,8,5,4,6,9,4,9};
        SimpleSort simpleSort = new SimpleSort();
        array = simpleSort.loopSort(array, 0);
        System.out.println("最终结果:"+Arrays.toString(array)+",num="+num);
    }
}

运行结果:

分次结果:[2, 5, 6, 8, 5, 4, 6, 9, 4, 9],i=1
分次结果:[2, 4, 6, 8, 5, 5, 6, 9, 4, 9],i=2
分次结果:[2, 4, 4, 8, 6, 5, 6, 9, 5, 9],i=3
分次结果:[2, 4, 4, 5, 8, 6, 6, 9, 5, 9],i=4
分次结果:[2, 4, 4, 5, 5, 8, 6, 9, 6, 9],i=5
分次结果:[2, 4, 4, 5, 5, 6, 8, 9, 6, 9],i=6
分次结果:[2, 4, 4, 5, 5, 6, 6, 9, 8, 9],i=7
分次结果:[2, 4, 4, 5, 5, 6, 6, 8, 9, 9],i=8
分次结果:[2, 4, 4, 5, 5, 6, 6, 8, 9, 9],i=9
最终结果:[2, 4, 4, 5, 5, 6, 6, 8, 9, 9],num=45

0 0
原创粉丝点击