在C 中编写一个简单的排序算法以及伪代码版本

Writing a simple sorting algorithm in c++, along with a pseudo code version

本文关键字:排序 简单 算法 版本 伪代码 一个      更新时间:2023-10-16

我正在尝试在C 中编写一种分类算法,然后用伪代码编写它,然后在伪代码中写下它,现在在pseudo中写下它并不是太糟糕了,但是将其删除了在我的脑海中,我正在挣扎,所以我向你们提出的问题:

我希望创建一种算法,该算法与两个整数(假设B和C)一起使用,并输出true,如果A包含一个大于B和小于C的元素,否则返回false。

For J <-- 1 to Length[A]
       Count <-- j+1
              while Count =< Length[A]

这是我的伪代码的开始,因为这似乎是合乎逻辑的事情,然后在C 中实现它,但是我发现自己四处绕圈创造循环,而不是取得太大进展。希望我所说的一切都有意义,有人可以将所有内容放在一起以创建某种形式的解决方案。谢谢。

从史蒂夫·麦康奈尔(Steve McConnell)的代码完成中,您的伪代码理想情况下应该比英语更像英语。我的拙见,您跳得太快了,无法实施。

这呢:

for each element in array
    check to see if element is between B and C
    if element is between B and C
        return TRUE
    else
        continue loop
next
return FALSE

这就是我从您的声明中收集的:

我想创建一种算法,该算法沿 使用两个整数(假设B和C)并输出为真,如果A包含一个 元素既大于b又小于c,否则 返回false。

我会从一个函数开始检查您关心的条件:给定数字,它属于指定范围:

boolean function in_range(A, B, C) {
    return (A > B) and (A < C);
}

从那里,它变成了通过数组扫描并调用功能的简单问题,将数组的每个元素作为A(以及提供为BCBC)。如果该函数在任何时候返回true,则可以停止扫描,外部功能也返回true(对于它的价值,C 11为这种情况提供std::any_of)。

您只是在数组中搜索与标准x> b&amp;&amp;x&lt;C.线性搜索会做 - 如果您要去一次搜索一次。如果必须多次进行搜索(除了log(数组的大小)),那么先排序然后进行二进制搜索是有意义的。

bool InRangeSearch(low, high)
{
  index = upper_bound(array, low);
  if(index==-1)
    return false;
  index2 = lower_bound(array, high);
  if(index2==-1)
    return true;
  return ((index2-1)>index);
}

pseudocode:

Quicksort(A as array, low as int, high as int)
    if (low < high)
        pivot_location = Partition(A,low,high)
    Quicksort(A,low, pivot_location - 1)
    Quicksort(A, pivot_location + 1, high)
Partition(A as array, low as int, high as int)
     pivot = A[low]
     leftwall = low
     for i = low + 1 to high
         if (A[i] < pivot) then
             leftwall = leftwall + 1
             swap(A[i], A[leftwall])
     swap(A[low],A[leftwall])
    return (leftwall)

程序代码:

#include <stdio.h>
void quickSort( int[], int, int);
int partition( int[], int, int);

int  main() 
{
    int a[] = { 7, 12, 1, -2, 0, 15, 4, 11, 9};
    int i;
    printf("nnUnsorted array is:  ");
    for(i = 0; i < 9; ++i)      printf(" %d ", a[i]);
    quickSort( a, 0, 8);
    printf("nnSorted array is:  ");
    for(i = 0; i < 9; ++i)      printf(" %d ", a[i]);
    printf("nn " );
    return 0;
}

void quickSort( int a[], int l, int r)
{
   int j;
   if( l < r ) 
   {
        j = partition( a, l, r);
       quickSort( a, l, j-1);
       quickSort( a, j+1, r);
   }
}

int partition( int a[], int l, int r) {
   int pivot, i, j, t;
   pivot = a[l];
   i = l; j = r+1;
   while( 1)
   {
    do ++i; while( a[i] <= pivot && i <= r );
    do --j; while( a[j] > pivot );
    if( i >= j ) break;
    t = a[i]; a[i] = a[j]; a[j] = t;
   }
   t = a[l]; a[l] = a[j]; a[j] = t;
   return j;
}