ClangStudy/quick_sort/quick_sort.c

125 lines
2.2 KiB
C
Raw Normal View History

2022-04-26 18:39:33 +09:00
#include <stdio.h>
2022-04-26 18:59:07 +09:00
#include <stdlib.h>
2022-04-26 18:39:33 +09:00
int
swap(
int *x,
int *y
)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
return 0;
}
/*************************************************************************
*************************************************************************/
int
quick_sort(
int *array, // ソートする配列
int left, // 左端
int right // 右端(※配列の要素数ではない)
)
{
int smaller_index;
int larger_index;
int pivot_index;
int pivot;
if ( left >= right ) {
return -1;
}
smaller_index = left;
larger_index = right;
pivot_index = left;
pivot = array[left];
while ( smaller_index < larger_index ) {
while ( array[smaller_index] < pivot )
{
smaller_index++;
}
while ( array[larger_index] > pivot )
{
larger_index--;
}
2022-04-27 18:32:13 +09:00
if ( array[smaller_index] < array[larger_index] ) {
break;
}
swap(&array[smaller_index], &array[larger_index]);
if ( array[smaller_index] == array[larger_index] ) {
2022-04-26 18:39:33 +09:00
smaller_index++;
}
}
quick_sort(array, left, larger_index - 1);
quick_sort(array, larger_index + 1, right);
return 0;
}
/***********************************
***********************************/
int
main()
{
2022-04-26 19:03:03 +09:00
int i;
int j;
int c;
int length = 0;
int read_line_size = 512;
char read_line[read_line_size];
FILE *fp;
2022-04-26 18:59:07 +09:00
char dataFile[] = "data.txt";
2022-04-26 19:03:03 +09:00
fp = fopen(dataFile, "r");
2022-04-26 18:59:07 +09:00
if ( fp == NULL ) {
printf("file can not open.\n");
return -1;
}
fseek(fp, 0, SEEK_SET);
while ( (c = fgetc(fp)) != EOF )
{
if ( c == '\n')
{
2022-04-26 19:03:03 +09:00
length++;
2022-04-26 18:59:07 +09:00
}
}
2022-04-26 19:03:03 +09:00
int array[length];
2022-04-26 18:59:07 +09:00
fseek(fp, 0, SEEK_SET);
2022-04-26 19:03:03 +09:00
for ( j = 0 ; j < length ; j++ )
2022-04-26 18:59:07 +09:00
{
fgets(read_line, read_line_size, fp);
array[j] = atoi(read_line);
}
fclose(fp);
2022-04-26 18:39:33 +09:00
printf("Length: %d\n", length);
quick_sort(array, 0, length - 1);
for ( i = 0 ; i < length ; i++ )
{
printf("%d", array[i]);
printf("\n");
}
return 0;
}