在C 中编写一个简单的排序算法以及伪代码版本
Writing a simple sorting algorithm in c++, along with a pseudo code version
我正在尝试在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
(以及提供为B
和C
的B
和C
)。如果该函数在任何时候返回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;
}
相关文章:
- 显示错误输出的简单数组排序程序
- 简单插入排序中的分段错误
- 在C std :: Priority_queue中反向字母排序顺序的简单方法
- 交替对数组进行排序的最简单方法是什么(例如:T,T,F 到 T,F,T,T,T,T,F,T,F,F,T,T,
- 从文本文件将整数读入简单的链表中.然后对整数列表进行气泡排序并读出到另一个文件
- 简单的数组排序/检查 划分和征服版本
- 在C 中编写一个简单的排序算法以及伪代码版本
- 一个简单的程序来对随机数进行排序
- C 简单字典:排序单词列表
- 最简单的气泡排序可能
- C++排序和读取此文件的最简单方法
- 运行这个简单的C ++程序(对结构数组进行排序)的更快方法
- 递归对向量进行排序的最简单方法
- 如何简单地按字母顺序对wxListCtrl的项目进行排序
- 返回垃圾的简单重新排序函数
- 简单std::排序不起作用
- 简单的c++向量排序
- 试图在c++中实现一个简单的一次性冒泡排序
- 单链表上的简单插入排序
- 为什么我的简单快速排序实现失败时,等效的元素在数组中