Bit vector sorting

Source: Internet
Author: User
Tags modulus

1. Bit vectors represent 0 ~ An integer of N is on a general machine. An integer of the int type has four bytes, a total of 32 bits. We can use different bits in these 32 bits to represent different integers; create an array [100]. Using the concept of a class, array [0] Stores 32 integers except 32 and equal to 0. Its modulus is represented by the corresponding bit in 32 bits, the corresponding array [1] Stores integers equal to 32 and equal to 1, for example, [cpp] int I = 5; // 5/32 = 0; 5% 32 = 5 int j = 12; // 12/32 = 0; 12% 32 = 12 int k = 31; // 31/32 = 0; 31% 32 = 31 int m = 34; // 34/32 = 1; 34% 32 = 2 int n = 40; // 40/32 = 1; 40% 32 = 8 at this time, the storage of these five numbers in the array should be as follows: array [0] = 0000 0100 0000 1000 0000 0000 0001 barray [1] = 0010 0000 1000 0000 0000 0000 0000 0000 barray [2] =... = array [99] = 0 modulus set 0 to 1 in the corresponding bit, which can represent the corresponding integer. 2. Bit vector sorting [cpp] int main (void) {int I; for (I = 0; I <N; I ++) clr (I); // reset the entire array while (scanf ("% d ", & I )! = EOF) set (I); // mark the number to be sorted with a bitvector in the array for (I = 0; I <N; I ++) if (test (I) // compares whether I is marked in the array. if yes, printf ("% d \ n", I) can be output in sequence ); return 0;} N is the maximum value of the integer to be sorted. the clr function resets the entire array, then, the set function marks the Integers to be sorted in the array using the bit vector notation. When we traverse 0 ~ When the integer is N, the integer to be sorted must be in the N number, as long as the test function is used to check whether I is marked in the array, we can see whether this number is the number we want to sort. If there is a mark, we can directly output it, so that we can achieve the purpose of sorting. 3. algorithm analysis time complexity: O (N); space complexity: O (N/32 + 1); 4. Source Code-code sharing

Related Article

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.