컴퓨터 엑셀 워드 포토샵 구글어스 WINDOWS JAVASCRIPT JAVA C++

 
Tuesday, October 24, 2006

C언어] 숫자 정수 int 배열 정렬(소트Sort소팅) 역순/내림차순 정렬


C언어에서, qsort() 함수를 사용하여 숫자(int)를 정렬하는 예제입니다.

문자열 배열을 정렬하는 방법과, qsort() 함수에 대한 설명은 여기에 있습니다: ▶▶ C언어] 문자열 배열 정렬(소트;Sort)역순 소팅, qsort 함수 사용법


숫자 정수 정렬 예제 소스 코드;Sort Example


소스 파일명: 0.cpp
※ 아래 박스 클릭 후, 키보드 화살표 키로 좌우 스크롤 가능함
#include <stdio.h>
#include <stdlib.h> // qsort()


int comparisonFunctionInt(const void *a, const void *b);


int main(void) {
  const int ELEMENTS = 11; // 요소 개수

  int array[ELEMENTS] = {
                                 59,
                                 24,
                                  0,
                                  4,
                               -357,
                                 35,
                                161,
                                 -3,
                               5455,
                                464,
                               6645 };


  qsort((void *)array, ELEMENTS, sizeof(array[0]), comparisonFunctionInt);

  for (int i = 0; i < ELEMENTS; i++)
    printf("%d\n", array[i]);

  return 0;
}




int comparisonFunctionInt(const void *a, const void *b) {

  if (*(int*)a <  *(int*)b) return -1;
  if (*(int*)a == *(int*)b) return  0;

  return 1;
}



실행 결과:
D:\Z>cl 0.cpp && 0.exe
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 13.10.3077 for 80x86
Copyright (C) Microsoft Corporation 1984-2002. All rights reserved.

0.cpp
Microsoft (R) Incremental Linker Version 7.10.3077
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:0.exe
0.obj
-357
-3
0
4
24
35
59
161
464
5455
6645

D:\Z>





역순(Descending Order;내림차순) 정렬


다음 함수처럼 a 와 b 의 위치를 약간 바꾸어 주면 됩니다.
int comparisonFunctionInt(const void *a, const void *b) {

  if (*(int*)b <  *(int*)a) return -1;
  if (*(int*)a == *(int*)b) return  0;

  return 1;
}



내림차순 정렬 실행 결과:
6645
5455
464
161
59
35
24
4
0
-3
-357



숫자 크기순 정렬 도구: ▶▶ 숫자 크기순 정렬 도구, 소트 소팅 툴; Numeric Sort Tool




tag: cpp
C언어 | C/C++ (Visual C++)

2 Comments:
At October 24, 2006 at 9:18 PM, Blogger CHIC-HANDSOME said...

good picture

 
At October 24, 2006 at 9:23 PM, Blogger mwultong said...

Thanks for visiting my blog..

(^_^)

 

Post a Comment

<< Home RSS 2.0 feed

구글 Google 에서 제공하는 무료 블로그 서비스인 블로거 Blogger 의 인터넷 주소는 www.blogger.com 입니다. Blogger 에 블로그를 만들면, blogspot.com 이라는 주소에 블로그가 생성됩니다.
블로그를 직접 방문하지 않고도 최신 게시물을 구독하려면 RSS 2.0 feed 주소를 리더기에 등록하시면 됩니다.
Previous Posts
Monthly Archives
Top