您的位置 首页 技术

如何在java中使用分治法中的快速排序解决排序问题

问题描述: 输入一个数字N后,输入N个数字,将N个数字排序后输出。 输入: 输出: 算法设计: 快速排序的基本思想是基于分治策略的,其算法思想如下: (1)分解:先从数列中取出一个…

问题描述:

输入一个数字N后,输入N个数字,将N个数字排序后输出。

输入:

3d8ce906ef1c4a0346d48ed74dd1d7a.png

输出:

f11ccb5337f24f5012d2f79a08455b4.png

算法设计:

快速排序的基本思想是基于分治策略的,其算法思想如下:

(1)分解:先从数列中取出一个元素作为基准元素.以基准元素为标准,将问题分解为两个子序列,使小于或等于基准元素的子序列在左侧,使大于基准元素的子序列在右侧.

(2)治理:对两个子序列进行快速排序.

(3)合并:将排好序的两个子序列合并在一起,得到原问题的解.

免费视频教程推荐:java学习视频

设当前待排列的序列为R[low:high],其中low≤high,如果序列的规模足够小,则直接进行排序,否则分3步处理:

(1)分解:在R[low:high]中选定一个元素R[pivot],以此为标注将要排序的序列划分为两个序列R[low:pivot-1]和R[pivot+1:high],并使序列R[low:pivot]中所有元素的值小于等于R[pivot],序列R[pivot+1:high]中所有的元素均大于R[pivot],此时基准元素已经位于正确的位置,它无需参加后面的排序.

(2)治理:对于两个子序列R[low:pivot-1]和R[pivot+1:high],分别通过递归调用快速排序算法来进行排序.

(3)合并:由于对R[low:pivot-1]和R[pivot:high]的排序是原地进行的,所以在R[low:pivot-1]和R[pivot+1:high]都已经排好序后,合并步骤无需做什么,序列R[low:high]就已经排好序了.

示例代码:

//程序目的:用分治法中的快速排序解决排序问题import java.util.Scanner;public class text2 {     public static void swap(int array[],int a,int b){//交换函数         int temp;         temp=array[a];         array[a]=array[b];         array[b]=temp;     }   public  static int Partition(int r[],int low,int high){        int i=low ;        int j=high;        int pivot=r[low];//基准元素        while(i<j) {            while (i < j && r[j] > pivot) //向左扫描                j--;                if (i < j) {                    swap(r, i++, j);                }                while (i < j && r[i] <= pivot) {//向右扫描                    i++;                }                if (i < j) {                    swap(r, i, j--);                }            }        return i;    }    public static void QuickSort(int R[],int low,int high){//快速排序递归算法         int mid;         if(low<high){             mid=Partition(R,low,high);//基准位置             QuickSort(R,low,mid-1);//左区间递归快速排序             QuickSort(R,mid+1,high);//右区间递归快速排序         }    }    public static void main(String args[]){         Scanner sc=new Scanner (System.in);         int i;         int n;//数据的个数        System.out.println("请先输入要排序元素的个数");        n=sc.nextInt();        System.out.println("请输入要排序的数据");        int []a=new int[n];         for (i=0;i<n;i++){             a[i]=sc.nextInt();         }         QuickSort(a,0,n-1);        System.out.println("排序后的数据");        for (i=0;i<n;i++){            System.out.print(a[i]+" ");        }        System.out.println();    }}

运行结果:

3e404f4418a907d544ca47b1369eaf5.png

相关学习教程推荐:java入门教程

以上就是如何在java中使用分治法中的快速排序解决排序问题的详细内容,更多请关注24课堂在线网其它相关文章!

本文来自网络,不代表24小时课堂在线立场,转载请注明出处:https://www.24ketang.cn/11481.html

为您推荐

返回顶部