gpt4 book ai didi

C编程: Pointer arithmetics instead of index operations

转载 作者:行者123 更新时间:2023-11-30 15:20:25 24 4
gpt4 key购买 nike

所以我对 C 编程非常陌生,在一个项目中,我得到了一个快速排序程序(我将在下面链接),并要求我使用指针算术重写快速排序程序,即没有任何索引操作。我该怎么做呢?我应该在代码中做什么来实现指针算术而不是索引操作?我的代码在这里:http://ideone.com/ku9EhU

#include<stdio.h>
#define N 10

void quicksort(int a[], int low, int high);
int split(int a[], int low, int high);

int main(void)
{
int a[N], i;

printf("Enter %d numbers to be sorted: ", N);
for (i = 0; i < N; i++)
scanf("%d", &a[i]);

quicksort(a, 0, N - 1);

printf("In sorted order: ");
for (i = 0; i < N; i++)
printf("%d ", a[i]);
printf("\n");

return 0;
}

void quicksort(int a[], int low, int high)
{
int middle;

if (low >= high) return;
middle = split(a, low, high);
quicksort(a, low, middle - 1);
quicksort(a, middle + 1, high);
}

int split(int a[], int low, int high)
{
int part_element = a[low];

for (;;) {
while (low < high && part_element <= a[high])
high--;
if (low >= high) break;
a[low++] = a[high];

while (low < high && a[low] <= part_element)
low++;
if (low >= high) break;
a[high--] = a[low];
}

a[high] = part_element;
return high;
}

最佳答案

数组索引访问a[i]等于指针算术*(a + i)

关于C编程: Pointer arithmetics instead of index operations,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30019330/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com