General Design of sorting algorithms

Source: Internet
Author: User
 

I have learned a lot about various sorting algorithms, such as Bubble sorting and fast sorting. But in books, I only want to introduce the sorting of several numbers. How can I apply it to real work. In fact, this is a universal design problem of algorithms. If you know C ++ STL, you will know this design idea and principle.

Here we mainly use quick sorting as an example (because I am personally interested in Java, so the implementation is implemented in Java. If I have time, I will implement it in C and C ++ respectively ). Knowledge preparation: Java language, implementation of fast sorting idea development environment: Eclipse, jdk1.6 Let's briefly review the idea of fast sorting (in fact this algorithm is not easy to explain, in short, I try my best, can leave a message or mail me (allwefantasy@gmail.com): Given an array, int [] array =, 37} This array is the array we need to sort. First, we should select a number, for example, 37 on the rightmost. We call it a pivot (why is it a pivot because it is translated in English ). Then we try to put the array smaller than 37 on the left of 37, and put it bigger than it on the right (no matter how we implement this placement algorithm, we will discuss it later. & note: the final result is that we put all the smaller ones on the left and the larger ones on the right, and the left and right sides of 37 are unordered, so there is an array:, (this result is achieved through a certain algorithm, as we will talk about later, it meets our above requirements .) Okay, now we know that we only need to sort the sum on the left of the pivot (that is, 37), and 37 must be in the correct position, so we don't have to worry about it (Why? Think about it with your toes ). We sorted 3, 8, and 15 in the same way, that is, we chose 15 as the pivot. Repeat the above steps and we can certainly determine the exact position of a number, for example, the true location of 15 should be 3, 8, 15, and 23. Then we sort 3, 8 again. (You may say, do you want to sort it? It can be seen at a glance that it is already in order, but don't forget, computers can be very stupid, it does not know), select the 8-bit hub, so the sorting result is 3, 8. After sorting 3 (in fact, the termination condition is reached, that is, there is only one element left), that is, the sorting result on the left of the final 37 is. In the same way, the right side can be launched. Now, let's talk about how to put the hub in the correct position. The algorithms are, and. We randomly choose a hub, we selected 37 in the previous step to facilitate programming. Otherwise, you can use (INT) math. random () * 11. Step 2: Left = 0, that is, left points to the first element of the array, that is, 42. Similarly, Right = 10 points to 37. Step 2: Left increments, if it is smaller than 37, it will increase progressively. If the number is greater than 37, for example, the first number is 42, Left = 0 at this time, stop, and perform step 3 step 3rd: Right-1 to decrease, if the number is greater than 37, it will decrease. If the number is smaller than 37, stop. For example, if the number is 3, that is, Right = 8, run Step 3: exchange 42 and 3. Continue step 1. Termination condition: If right-left <0, the termination will not be known. Some may prefer to use programs to understand the idea of algorithms. The following shows the Implementation Program:

public int partition(int left,int right,int pivot){int leftPtr=left-1;int rightPtr=right;while(true){while(pivot>array[++left]){}while(rightPtr>0&&pivot<array[--right]){}if(leftPtr<rightPtr)swap(leftPtr,rightPtr);else break;}swap(leftPtr,right);return leftPtr;}public void swap(int left,int right){ int temp=array[left];array[left]=array[right];array[right]=temp;}}

Well, the above solves the problem of putting a hub. How can we implement recursive loops and arrange all the hubs?

In fact, according to the previous analysis, we have a clear idea. The following code is used to describe it directly;

Note that the preceding partition function returns the Pivot Position, which should be sorted by the pivot, so no sorting is required. Therefore, it is not included in the recursion of quicksort.
The entire program is as follows:

public class QuickSort {int size=20;int[] array=new int[size];public void quickSort(int left,int right){if(right<=left)return ;else{int pivot=array[right];int leftPtr=partition(left,right,pivot);quickSort(left,leftPtr-1);quickSort(leftPtr+1,right);}}public int partition(int left,int right,int pivot){int leftPtr=left-1;int rightPtr=right;while(true){while(pivot>array[++left]){}while(--right>0&&pivot<array[--right]){}if(leftPtr<=rightPtr)swap(leftPtr,rightPtr);else break;}swap(leftPtr,right);return leftPtr;}public void swap(int left,int right){ int temp=array[left];array[left]=array[right];array[right]=temp;}}

Now that we have reviewed the algorithm, we have learned how to use it. For example, I am not necessarily sorting numbers, maybe letters. In addition, the data to be sorted is not necessarily included in the array, but may be included in the vector and hashtable. More advanced data may be sorted by uncertain data types retrieved from the database, as mentioned above, this involves the Universal Design of algorithms.

Let's take a look at the analysis. We cannot use a general Sorting Algorithm because the data types are different, but the idea of the Sorting Algorithm is different. When writing General sorting codes, a problem is that the comparison operation must be performed based on the actual object type to achieve correct sorting, the solution is to "separate the changed things from those that remain unchanged ". Here, the unchanged code is a general sorting algorithm, and the actual comparison method of the object needs to be changed every time you use it. Let's first implement a comparative interface (interface-oriented programming is advocated by Java, and spring is a strong proof of this behavior ). Interface compare {Boolean lessthan (Object sou, object des); Boolean lessthanorequal (Object sou, object des );
} This is a comparison class. Below is the class that I changed the previous Quick Sort;
package com.hailin.www;import java.util.Vector;public class QuickSortVector extends Vector{private Compare compare;public QuickSortVector(Compare com){this.compare=com;}public void sort(){quickSort(0,size()-1);}public void quickSort(int left,int right){if(right<=left)return ;else{Object pivot=elementAt(right);int leftPtr=partition(left,right,pivot);quickSort(left,leftPtr-1);quickSort(leftPtr+1,right);}}public int partition(int left,int right,Object pivot){int leftPtr=left-1;int rightPtr=right;while(true){while(compare.lessThan(elementAt(++leftPtr), pivot)){}while(rightPtr>0&&compare.lessThan(pivot, elementAt(--rightPtr))){}if(leftPtr<rightPtr)swap(leftPtr,rightPtr);else break;}swap(leftPtr,right);return leftPtr;}public void swap(int left,int right){ Object temp=elementAt(left);setElementAt(elementAt(right), left);setElementAt(temp, right);}}

In fact, you only need to rename the original int type as the object root class. In addition, although the array efficiency is relatively high, it is not flexible and limited by the length, providing fewer methods, so here we inherit the Vector class. Therefore, the size (), elementat (), and setelementat () methods are inherited from the parent class. Now we can clearly see that if we want to compare the character escape, we only need to implement the Compare interface of the character escape class. The following describes how to implement the comparestring class.

public class CompareString implements Compare {@Overridepublic boolean lessThan(Object sou, Object des) {return ((String)sou).toLowerCase().compareTo(((String)des).toLowerCase())<0;}@Overridepublic boolean lessThanOrEqual(Object sou, Object des) {return ((String)sou).toLowerCase().compareTo(((String)des).toLowerCase())<=0;}}
Note that the compareto () method compares the order of the object with the specified object. It returns an integer. If the object is smaller than, equal to, or greater than the specified object, a negative integer, zero, or positive integer is returned. Therefore, we must judge and return a Boolean value.

The following is a test procedure:

import java.util.Enumeration;public class TTest {public static void main(String[] args) {QuickSortVector qsv= new QuickSortVector(new CompareString());qsv.addElement("a");qsv.addElement("M");qsv.addElement("b");qsv.addElement("K");qsv.addElement("z");qsv.addElement("y");qsv.sort();Enumeration e = qsv.elements();while(e.hasMoreElements())System.out.println(e.nextElement());}}
Program result: abkmyz also made a small mistake when writing this program. It took only half a day to debug the program in a single step. I hope you can pay attention to the following:
if(leftPtrint size=20;int[] array=new int[size];public void quickSort(int left,int right){if(right<=left)return ;else{int pivot=array[right];int leftPtr=partition(left,right,pivot);quickSort(left,leftPtr-1);quickSort(leftPtr+1,right);}}
From the above program, we can see that to compare other types of objects, you only need to implement the corresponding compare class. Note. During the test, we also had a qsv. Sort (). In fact, we can rewrite the elments () method in the quicksortvector class, so that the encapsulation is better. At the same time, we can cover more original parent class methods to make them more suitable for our needs. I will write it here today... I hope to have more exchanges with you. ------------------------------------ Welcome to the launch of the new website Website Transaction CenterYou can purchase or sell your website here.
Website information publishing centerVarious transaction information is released here. At the same time
Free use of some software (with source code ).
Website Blog systemYou can register your own blog here. An unlimited number of blogs under one account
Contact info: Support@websiteempire.cn
QQ: 563828566
MSN: zhuhailin123@hotmail.com

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.