我该如何用C编写此伪代码?

时间:2019-12-17 08:29:46

标签: c quicksort pseudocode

我真的需要一些帮助来用C编写此伪代码,我拥有伪代码,而且我对伪代码真的很不好。所以我真的需要一些帮助来用C编写。 伪代码用于递归Quicksort算法,并使用大量while循环。 所以我真的很希望som帮助将伪代码转换为C代码。 伪代码可以在图像中看到。

 Algorithm 1: quicksort(a, i1, i2)
 n ← i2 − i1 + 1;
 if n ≤ 1 then
 return;
 else
 m ← partition(a, i1, i2);
 n1 ← m − i1;
 n2 ← i2 − m;
 if n1 < n2 then
 quicksort(a, i1, m − 1);
 quicksort(a, m + 1, i2);
 else
 quicksort(a, m + 1, i2);
 quicksort(a, i1, m − 1);

Algorithm 2: partition(a, i1, i2)
// This algorithm partitions the array segment a[i1 . . . i2]
// Extract the bound from the end to create a hole
b ← a[i2];
// Initialize the lower and upper pointers
l ← i1;
u ← i2;
// Loop until the array is partitioned
while l < u do
// Scan the lower pointer until a misplaced element is found
while l < u and a[l] ≤ b do
l ← l + 1;
// Move the misplaced element to the hole
if l < u then
a[u] ← a[l];
u ← u − 1;
// Scan the upper pointer until a misplaced element is found
while l < u and a[u] ≥ b do
u ← u − 1;
// Move the misplaced element to the hole
if l < u then
a[l] ← a[u];
l ← l + 1;
//At this point l = u
// Replace the bound between the partitioned segments
a[l] ← b;
// Return the index of the correctly placed element between segments
return l;

我到目前为止编写的代码:

int partition(int arr[], int i1, int i2){
  int b = arr[i2];
  int l = i1;
  int u = i2;

  while(u < l){

    while(l < u && arr[l] <= b){
      l++;
    }
    if(l < u){
      arr[u] = arr[l];
      u--;
    }

    while (l < u && arr[u] >= b){
      u--;
    }
    if (l < u){
      arr[l] = arr[u];
      l++;
    }
  }

  arr[l] = b;
  return l;
}

void quicksort(int arr[], int i1, int i2){
  int n = i2 - i1 + 1;
  if(n <= 1){
    return;
  }
  else {
    int m = partition(arr, i1, i2);
    int n1 = m - i1;
    int n2 = i2 - m;

    if (n1 < n2){
      quicksort(arr, i1, m-1);
      quicksort(arr, m+1, i2);
    }
    else {
      quicksort(arr, m+1, i2);
      quicksort(arr, i1, m-1);
    }


  }


}

但是感觉不正确,感觉好像我缺少一堆指针或其他东西。

0 个答案:

没有答案