Algorithm class algorithm part I week 3 duplicate element sorting-three-way fast duplicate keys

Source: Internet
Author: User

In many cases, sorting aims to classify data, which has many duplicate values.

  • Population statistics by age
  • Delete duplicate emails in the email list
  • Sort job seekers by University

If you sort repeated data using a normal fast sort, the complexity of N ^ 2 will be caused, but there is no such problem between the merge sort and the three-way fast sort.

The comparison between 1/2nlgn and nlgn

Three routes

Objective: To divide data into three intervals (3-way partitioning)

  • The elements in the LT and GT ranges are equal to the comparison element V.
  • Lt. The element on the left is smaller than v.
  • The element on the Right of GT is larger than v.

Performance

The complexity of the three-way fast sorting is smaller than that of the normal fast sorting, mainly depending on the number of duplicate data in the data. The more duplicate data, the more complex the three-way fast sorting is.

JAVA Implementation

private static void sort(Comparable[] a, int lo, int hi){  if (hi <= lo) return;  int lt = lo, gt = hi;  Comparable v = a[lo];  int i = lo;  while (i <= gt)  {    int cmp = a[i].compareTo(v);    if     (cmp < 0) exch(a, lt++, i++);    else if (cmp > 0) exch(a,i,gt--);    else              i++;  }  sort(a, lo, lt - 1);  sort(a, gt + 1, hi);    }

 

  • A [I] <v: Switching A [lt] And a [I], LT and I increase by 1, respectively.
  • A [I]> V: Switching A [gt] And a [I], GT decreases by 1
  • A [I] = V: I increments by 1
  • Note: GT does not scan independently. The value of GT is decreased only after a [I] is exchanged with a [gt ].

 

Algorithm class algorithm part I week 3 duplicate element sorting-three-way fast duplicate keys

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.