交换排序

一、冒泡排序

     依次比较相邻两个数,将较大的交换到右边,重复此过程,直至有序

package com.algorithm.sort;

public class BubbleSort implements Sort {

    @Override
    public void sort(int[] arr) {
        // TODO Auto-generated method stub
        int exchange = arr.length -1;
        boolean isExchanged = true;
        
        while(isExchanged){
            isExchanged = false;            
            int max = exchange;
            
            for (int i = 0; i < max; i++){
                if (arr[i] > arr[i+1]){
                    int temp = arr[i];
                    arr[i] = arr[i+1];
                    arr[i+1] = temp;
                    
                    isExchanged = true;
                    exchange = i;
                }
            }
        }
    }
    
    public static void main(String[] args){
        int[] arr = {1,3,2,6,9,4,5,7,8,56,7,8,9,3,88};
        Sort sort =new BubbleSort();
        sort.sort(arr);
        
        for(int a: arr){
            System.out.print(a + " ");
        }
    }
}

 

二、快速排序

将较大的数都交换到右边,较小的数都交换到左边,这样划分成两个序列,再分别对两个序列重复以上过程

package com.algorithm.sort;

public class QuickSort implements Sort {

    @Override
    public void sort(int[] arr) {
        // TODO Auto-generated method stub
        quickSort(arr,0,arr.length-1);
    }
    private void quickSort(int[] arr, int first, int end) {
        if (first < end){
            int pos = partition(arr, first, end);
            quickSort(arr, first, pos-1);
            quickSort(arr, pos+1, end);
        }
    }
    
    private int partition(int[] arr, int first, int end){
        while (first < end){
            //右扫
            while (first < end && arr[first] <= arr[end]) end--;
            if (first < end){
                swap(arr, first, end);
                first++;
            }
            //左扫
            while (first < end && arr[first] <= arr[end]) first++;    
            if (first < eand){
                swap(arr, first, end);
                end--;
            }
        }
        return first;
    }
    
    private void swap(int arr[], int i, int j){
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    public static void main(String[] args){
        int[] arr = {1,3,2,6,9,4,5,7,8,56,7,8,9,3,88};
        Sort sort =new QuickSort();
        sort.sort(arr);
        
        for(int a: arr){
            System.out.print(a + " ");
        }
    }
}

 

转载于:https://www.cnblogs.com/xuruhong/p/3281112.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值