# Sorting algorithm--quick-line thinking

Source: Internet
Author: User
Tags sorts

Quick Sort

1. Thought

Fast sorting divides an array into two arrays and then sorts the two arrays independently, which is a recursive algorithm.

First randomly selects a shard element temp (typically the first element of the array), places the number less than temp on the left side of temp, and places the number greater than temp on the right side of temp.

The fast and heap sorts are like, they all divide an array into two sub-arrays, all of which belong to a recursive algorithm. But the difference is that the complexity of the fast-row space is O (1), and the Heap is O (n),

The quick rank is in-place sort, only needs a very small auxiliary stack, the time complexity is NLOGN.

2. Code implementation (Java)

Public class Quick {

Public static void sort (int[] a,int lo,int hi) {
if (Hi<=lo) return;
//Shard
int J = partition (A,lo,hi);
sort (a,lo,j-1);
sort (a,j+1,hi);

}
//a[j] is the Shard element that scans right from the left end of the array until it finds an element greater than or equal to it
//Start scanning to the right of the array until you find an element that is less than or equal to it, and swap the two elements for a position.
public static int partition (int[] a,int lo,int hi) {
//Left/Right scan array
int j = lo;
int i = hi+1;;
int v = A[lo];
While (true) {
While (V>=a[++j]) {
if (j==hi) break;
//j++;
}
While (V<=a[--i]) {
if (i==lo) break;
//i--;
}
if (j>=i) {
Break ;
}
int t = a[i];
A[i] = a[j];
a[j] = t;
}
A[lo] = a[j];
A[j] = v;
return J;
}

Public static void Main (string[] args) {
int[] A = {49,78,23,34,67,45,73,90,120,12,20,9,5};
int lo = 0;
int hi = a.length-1;
sort (a,lo,hi);
for (int i=0;i<a.length;i++) {
System.out.print (a[i]+ "");
}

}

}

Sorting algorithm--quick-line thinking

Related Keywords:

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.