Introduction to algorithms learning notes-counting and sorting algorithms

Source: Internet
Author: User
/*** Counting sorting assume that each of the N input elements is an integer between 0 and K. Here K is an integer. * The basic idea is: For each input element, determine the number of elements smaller than X, so that X can be directly placed in its position in the final output array. *AlgorithmThe complexity is O (n + k). When k = O (n), the running time is O (n) * another characteristic: the counting sorting is stable, the relative order of elements with the same value in the output array is the same as the order of the elements in the input array */public class countingsort {/*** @ Param A // stores the original array to be sorted * @ Param B // The array that stores the sorting result * @ Param K // each element in a is between 0 and K */static void countingsort (int A [], int B [], int K) {// The C array is a temporary storage area. c stores the number of times each element appears in a from 0 to K, therefore, the length of C is k + 1. Int C [] = new int [k + 1]; // The number of elements in C [I] That store equal to I (0 = <I <= K) for (INT I = 0; I <. length; I ++) C [A [I] ++; // C [I] stores the number of elements smaller than or equal to I for (INT I = 1; I <= K; I ++) C [I] = C [I] + C [I-1]; // Since C [I] stores less than or equal to the number of I elements, therefore, I should be placed in the C [I] position in array B (because the array starts from 0, so 1 is required) for (INT r =. length-1; r> = 0; r --) {int I = A [R]; B [C [I]-1] = I; // every time C [I] minus 1, it can ensure that the next element is the same as I, which falls in the previous position C [I] --;} of B [C [I]-1]. // test ..... public static void main (string [] ARGs) {int A [] = {2, 5, 3, 0, 2, 3, 0}; int B [] = new int [8]; countingsort (A, B, 5); For (INT I = 0; I <B. length; I ++) system. out. println (B [I]);}

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.