연결리스트에서 정렬하기...

hurryon의 이미지

냠냠...오래간만에 자료구조 책을 열어 놓고 보고 있습니다만...역시 어렵네요. 아마도...머리가 영...

단순 연결리스트입니다. 단순 연결리스트로 만들어진 녀석들을 정렬하고 싶은데...잘 안되네요. 오름차순이든 내림차순이든 정렬해 보려고 하는데...아마도 응용력이 상당히 떨어지는 듯.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>

struct data
{
    int index;
    int number; 

    struct data *next;
};

typedef struct data link;
typedef link *node;

node head;

int get_random()
{
    unsigned char ran, mask, i;
    struct timeval now_time;

    ran = 0;

    for(i = 0 ; i < 1 ; i++)  
    {
        gettimeofday(&now_time, 0);

        mask = now_time.tv_usec / 2;
        mask <<= i;
        ran |= mask;
    }
    
    return(ran);
} 

void node_init()
{
    node tmp;
    int i;  

    printf("Function: %s Start!\n", __func__);

    for(i = 0; i < 10; i++)
    {
        tmp = (link *)malloc(sizeof(link));

        if(tmp == NULL)
        {
            fprintf(stdout, "Out of memory, node_init\n");
            exit(1);
        }

        else
        {
            tmp->index = i;
            tmp->number = get_random();

            printf("index: %2d number: %4d\n", tmp->index, tmp->number);

            tmp->next = head; 
            head = tmp;
        }
    }
}

void node_sort()
{
    node previous;
    node current;
    struct data *next;

    previous = NULL;
    current = head;

    printf("Function: %s Start!\n", __func__);

    while(current != NULL)
    {
        if(previous == NULL)
        {
            previous = current;
        }

        else
        {
            if(previous->number > current->number)
            {
                printf("%d %d\n", previous->number, current->number);

                next = current->next;
                previous->next = next;
                current->next = previous->next;

                current = current->next;
            }

            else
            {
                current = current->next;
            }
        }
    }

}

void node_print()
{
    node tmp;

    tmp = head;

    printf("Function: %s Start!\n", __func__);

    while(tmp != NULL)
    {
        printf("index: %2d number: %4d\n", tmp->index, tmp->number);

        tmp = tmp->next;
    }
}

int main()
{
    if((head = (link *)malloc(sizeof(link))) == NULL)
    {
        fprintf(stdout, "Out of memory\n");
        exit(1);
    }

    head = NULL;

    node_init();

    node_print();

    node_sort();

    node_print();

    return(0);
}

결과는 다음과 같이 나옵니다.

[hurryon@localhost ~/c/0909]$ ./simple_link 
Function: node_init Start!
index:  0 number:  114
index:  1 number:  236
index:  2 number:   88
index:  3 number:  193
index:  4 number:   42
index:  5 number:  146
index:  6 number:   12
index:  7 number:  119
index:  8 number:  224
index:  9 number:   72
Function: node_print Start!
index:  9 number:   72
index:  8 number:  224
index:  7 number:  119
index:  6 number:   12
index:  5 number:  146
index:  4 number:   42
index:  3 number:  193
index:  2 number:   88
index:  1 number:  236
index:  0 number:  114
Function: node_sort Start!
72 12
72 42
Function: node_print Start!
index:  9 number:   72
index:  3 number:  193
index:  2 number:   88
index:  1 number:  236
index:  0 number:  114
[hurryon@localhost ~/c/0909]$ 

으흠. 이중 연결리스트로 해결하는 방법을 원하는게 아닙니다. 흐.

sliver의 이미지

퀵소트를 이용해서 짜봤습니다.

node quicksort_helper(node h)
{
  node pivot = h;
  node left=NULL,right=NULL;
  if(pivot==NULL) return NULL;
  h = h->next;
  while(h!=NULL) {
    node *which_side;
    node tmp;
    if(h->number > pivot->number) which_side = &right;
    else which_side = &left;
    tmp = h;
    h = h->next;
    tmp->next = *which_side;
    *which_side = tmp;
  }
  left = quicksort_helper(left);
  right = quicksort_helper(right);
  pivot->next = right;
  if(left==NULL) h = pivot;
  else {
    h = left;
    while(left->next!=NULL) left = left->next;
    left->next = pivot;
  }
  return h;
}
    
void node_quicksort()
{
  head = quicksort_helper(head);
}

리스트 크기가 별로 크지 않다면 insertion sort도 괜찮을 것 같네요.

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.