base sort using C++

來源:互聯網
上載者:User

設有一個整數鏈表,其中表元的索引值為不超過三位元的整數,不妨設索引值形式ABC。其中A表示索引值的百位元,B為十位元,C為個位元。首先按索引值中的個位值C對鏈表作分拆和連結,先把鏈表分拆成多至10個隊列鏈表,然後以C的值從0至9的順序把分拆後的十個隊列鏈表重新收整合一個鏈表。接著依次對索引值中的B和A進行同樣的分拆和連結操作,則最後收集起來的鏈表是按索引值從小到大排序連結的。如有一個鏈表按它們的索引值其表元的連結順序依次為:
35,298,832,932,38,635,22,15,48,118,128,138,148,158

// binSort.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include<stdio.h>
#include<stdlib.h>

#define KEYN 3
int inputNumber[]={35,298,832,932,38,635,22,15,48,118,128,138,148,158};
#define N sizeof inputNumber/sizeof inputNumber[0]

struct element
{
 int key;
 struct element *next;
};

void baseSort(struct element **h)
{
 int i,j,factor = 1;
 struct element *linkList[10],*tailOfLinkList[10],*p,*u;

 for(i=0,p=*h;i<KEYN;factor*=10,i++)
 {
  for(j=0;j<10;j++)
  {
   linkList[j] = NULL;
  }

  while(p)
  {
   u = p->next;
   j = (p->key/factor)%10;

   if(linkList[j]==NULL)
   {
    linkList[j] = p;
   }
   else
   {
    tailOfLinkList[j]->next = p;
   }

   tailOfLinkList[j] = p;
   p->next = NULL;
   p = u;
  }
  
  p = NULL;

  for(j=0;j<10;j++)
  {
   if(linkList[j] == NULL)
   {
    continue;
   }

   if(p == NULL)
   {
    p = linkList[j];
   }
   else
   {
    u->next = linkList[j];
   }

   u = tailOfLinkList[j];
  }
 }

 *h = p;
}

void main()
{
 struct element *h,*u;
 int i;
 h = NULL;

 for(i=0;i<N;i++)
 {
  u=(struct element *)malloc(sizeof(struct element));
  u->key = inputNumber[i];
  u->next = h;
  h = u;
 }

 baseSort(&h);

 for(u=h;u;u=u->next)
 {
  printf("%4d",u->key);
 }

 scanf(" ");
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.