数组 快速排序 递归算法

时间:2021-07-14 04:12:50
数组 快速排序  递归算法
import javax.swing.*;import java.awt.*;import java.awt.event.*;import java.text.*;public class Exercise7_39 extends JApplet implements ActionListener {final int MAX=16;int array[];int times=0;JTextArea outputArea;JScrollPane scroller;JButton sort;JButton createArray;Font font=new Font("Monospaced", Font.PLAIN|Font.BOLD, 12);DecimalFormat digits=new DecimalFormat("000");public void init(){array=new int[MAX];for(int counter=0; counter<MAX; counter++){array[counter]=(int)(Math.random()*100+1);}outputArea=new JTextArea(30, 100);outputArea.setFont(new Font("Monospaced", Font.PLAIN, 12));scroller=new JScrollPane(outputArea);sort=new JButton("sort");createArray=new JButton("create Array");sort.addActionListener(this);createArray.addActionListener(this);Container container=getContentPane();container.setLayout(new FlowLayout());container.add(scroller);container.add(createArray);container.add(sort);outputArea.append("原始数组:\n");printArray(-1);outputArea.append("\n\n");}public void actionPerformed(ActionEvent actionEvent){if(actionEvent.getSource()==createArray){times=0;for(int counter=0; counter<MAX; counter++){array[counter]=(int)(Math.random()*100+1);}outputArea.setText("原始数组:\n");printArray(-1);outputArea.append("\n\n");}elseif(actionEvent.getSource()==sort){times=0;outputArea.setText("");outputArea.append("原始数组:\n");printArray(-1);outputArea.append("\n\n");quickSort( 0, MAX-1);outputArea.append("\n 最终结果 为:\n");printArray(-1);}}public int partion( int min, int max){int present=min;int left=min;int right=max;while(left<right){for(right=max; right>=present; right--){if(array[right]<=array[present]){exchange(right,present);present=right;}}for(left=min; left<=present; left++){if(array[left]>=array[present]){exchange(left,present);present=left;}}}return present;}public void quickSort( int min, int  max){if(min>max||min>MAX-1||max<0){return;}int middle=partion(min, max);times++;outputArea.append("第"+digits.format(times)+"次排序:\t");printArray(middle);quickSort(min, middle-1);quickSort(middle+1, max);}public void printArray(int middle){String output="";for(int counter=0; counter<MAX; counter++){if(counter==middle){output+=" #" + digits.format(array[counter]);}elseoutput+="  "+ digits.format(array[counter]);}outputArea.append(output+"\n");}public void exchange( int a, int b){int temp=array[a];array[a]=array[b];array[b]=temp;}}