A scary looking algorithm "Microsoft interview to 100 question 49th"

Source: Internet
Author: User

Title Requirements:

How to sort N numbers requires time complexity O (n). The spatial complexity is O (1).

Topic Analysis:

Strictly speaking, the condition given by this problem is not complete. If the size of these n numbers spans large (1~ infinity), then the requirement is certainly not reached.

If the size of n numbers is within a certain range (such as 0~65535), you can use the hash table method. defined as int hash[65536], occupying a memory space fixed to sizeof (int) *65536, the space complexity is O (1).

So how is the time complexity O (N)? That is, you can iterate through the array a few times to sort through. In fact, we can go through the array again, and then traverse through the hash space to output the sorted result.

As an example, for the sake of simplification, assuming that all numbers are between 0~10, define int hash[10] and initialize hash[0~9]=0;

The number of n in the original array is: {7,4,3,4,7,2,1,9}.

The first time in the group, each hash[a[i]]++ processing, so the result is hash[7]=2,hash[3]=1 ....

The second passes through the hash array, from hash[0]~hash[9], when hash[i] = x, continuously outputs X i. The result of this final output is 1 2 3 4 4 7 7 9.

The time complexity is O (N). The spatial complexity is O (1). Done ....

Code implementation:

  

#include <iostream>using namespacestd;Const intN =8;Const intHash_space =65536;voidSort (intA[],intNinthash[]);intMainvoid){    intA[n] = {7,4,3,4,7,2,1,9}; intHash[hash_space] = {0};    Sort (A,n,hash); return 0;}voidSort (intA[],intNinthash[]) {     for(intI=0; i<n;i++) {Hash[a[i]]++; }     for(intI=0; i)    {         while(Hash[i]) {cout<< I <<" "; Hash[i]--; }} cout<<Endl;}

A scary looking algorithm "Microsoft interview to 100 question 49th"

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.