数据结构之 移位操作
题目:
unsigned int 型一个数组,按照比特位中“1”的个数对数组元素进行从小到大排序,如果含有“1”的个数相同,按从小到大排序,unsigned int 32位。
函数原型: int sort(unsigned int *a, int len);
代码:
// Test1.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include "stdio.h"#include "iostream"using namespace std;struct DATA{unsigned int num;unsigned int count; // 记录unsigned int 变量中比特位为1的个数};int sort(unsigned int *arr, int length);int _tmain(int argc, _TCHAR* argv[]){unsigned int num[5]={2,10,4,15,5};sort(num,5);system("pause");return 0;}// 对数组中的元素通过每个元素的比特位中1的个数进行排序,包含个数相同的采用元素大小进行排序int sort(unsigned int *arr, int length){DATA *p=new DATA[length];if (p==NULL){return 0;}for (int i=0;i<length;i++){p[i].num=arr[i];p[i].count=0; // 初始化}// 统计比特位1的个数int BIT_SIZE=sizeof(unsigned int)*8;unsigned int FLAG_CP=0x0001; // 用于进行按位与unsigned int FLAG_YES=0x0001;unsigned int FLAG_NO=0x0000;for(int i=0;i<length;i++){// 每个数进行统计unsigned int temp=p[i].num;for(int j=0;j<BIT_SIZE;j++){unsigned result=temp&FLAG_CP;if (result==FLAG_YES){p[i].count++;}temp=temp>>1;}}// 根据比特位1进行排序for (int i=0;i<length-1;i++){for (int j=i+1;j<length;j++){if (p[j].count<p[i].count){DATA temp=p[j];p[j]=p[i];p[i]=temp;}else{if (p[j].count==p[i].count){// 比特位1相同,按照元素值大小进行排序if (p[j].num<p[i].num){DATA temp=p[j];p[j]=p[i];p[i]=temp;}}}}}// 输出排序结果for(int i=0;i<length;i++){printf("%5d",p[i].num);}printf("\n");return 1;}