0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

WindowsとLinuxでqsort関数の結果が異なる場合がある

Last updated at Posted at 2023-02-24

qsort関数は、クイックソート機能を提供している標準ライブラリー関数です。(stdlib.hで定義)
qsort関数は、比較結果が等値となるデータが複数含まれる集合に対して実行すると、Windows(VC)とLinux(gcc)でソート結果が異なる可能性があります。

環境

  • Windows10 + VisualStudio2017
  • Ubuntu 20.04.5LTS + gcc9.4.0

再現コード

main.c
#include <stdio.h>
#include <stdlib.h>

typedef struct
{
	int age;
	int id;
} PERSON;

int compare(const void* x, const void* y)
{
	if (((PERSON*)x)->age > ((PERSON*)y)->age) {
		return 1;
	}
	else if(((PERSON*)x)->age < ((PERSON*)y)->age) {
		return -1;
	}
	else {
		return 0;
	}
}

int main()
{
	PERSON array[] = {
		{4, 100},
		{3, 200},
		{2, 1000},
		{1, 1100},
		{3, 300},
		{3, 400},
		{3, 800},
		{3, 600},
		{3, 500},
		{3, 700},
		{3, 900},
	};
	int num = sizeof(array) / sizeof(array[0]);
	qsort(array, num, sizeof(PERSON), compare);

	printf("age id\n");
	for (int i = 0; i < num; i++) {
		printf("%d %d\n", array[i].age, array[i].id);
	}
    return 0;
}

実行結果

[Windows] [Ubuntu]
age id    age id
1 1100    1 1100
2 1000    2 1000
3 200     3 200
3 400     3 300
3 300     3 400
3 900     3 800
3 800     3 600
3 600     3 500
3 500     3 700
3 700     3 900
4 100     4 100

対策案

  1. 比較関数で、比較する項目を増やす
  2. 自力でクイックソートを実装する
    参考)C言語でクイックソート
0
0
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?