Write code into pseudocode - arrays

I need help to write this code into pseudocode
public void quickSort(int[] A, int p, int r) {
if (p < r) {
int q = partition(A, p, r);
quickSort(A, p, q);
quickSort(A, q + 1, r);
}
}
private int partition(int[] A, int p, int r) {
int x = A[p]; // pivot element x
int i = p - 1;
int j = r + 1;
// partition
while (true) {
do {
j--;
} while (A[j] > x);
do {
i++;
} while (A[i] < x);
if (i < j)
swap(A, i, j);
else
return j;
}
}
private void swap(int[] A, int i, int j) {
int tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
}

for each (unsorted) partition
set first element as pivot
storeIndex = pivotIndex + 1
for i = pivotIndex + 1 to rightmostIndex
if element[i] < element[pivot]
swap(i, storeIndex); storeIndex++
swap(pivot, storeIndex - 1)

Related

Having issues with outputting the number of searches of a Binary search algorithm

I'm stuck with trying to get the number of searches done within a Binary search algorithm.
The goal is to test how many searches are done depending on how much data is put into the algorithm.
The program in question
//CBinarysearch.c//
#include <stdio.h>
#include <time.h>
#define NUM 100
#define MAX 200
int binary_s(int a[], int n, int s) {
int lo, hi, mid;
int c = 0;
lo = 0;//loの初期化
hi = n-1;//hiの初期化
while (lo <= hi) {
mid = (lo + hi) / 2;//midの初期化
c++;
if (s == a[mid]) break;//探索値がmidと同じ値となればloopを終了
if (s > a[mid])//探索値がmidより大きい場合
lo = mid + 1;//loの値を;1してmidへ移動
else//探索値がmidより小さい場合
hi = mid - 1;//hiの値をー1してmidへ移動
}
if (lo <= hi)
printf("The numerical value %d is in array %d (array element %d)\n", s, mid+1, mid);
else
printf("Could not be located.\n");
return c;
}
void shuffle(int a[]) {
unsigned int i, j;
int tmp;
i = MAX - 1;
while (i > 0) {//シャッフルのためのLoop
j = rand() % (i + 1);//jの値をランダム化
tmp = a[j];
a[j] = a[i];
a[i] = tmp;
i--;
}
}
int quicksort(int a[], int first, int last) {
int i, j, temp, x;
i = first;
j = last;
x = (a[i] + a[j]) / 2;//基準値は平均
while (1) {
while (a[i] < x) i++;
while (a[j] > x) j--;
//iがjより大きくなればwhile loopが解除される
if (i >= j) break;
//a[i]とa[j]を入れ替える
temp = a[i];
a[i] = a[j];
a[j] = temp;
i++;
j--;
}
if (first < i-1) quicksort(a, first, i-1);
if (j + 1 < last) quicksort(a, j + 1, last);
return 0;
}
int main(void) {
int a[NUM];
int i;
int count;
int s;
srand((unsigned int)time(NULL));
i = rand() % NUM;
s = a[i];
for (i = 0; i < NUM; i++) {//整列数列の作成
a[i] = i + 1;
}
shuffle(a);//Fisher-Yates shuffle
quicksort(a, 0, NUM-1);//クイックソートの呼び出し
count = binary_s(a, NUM, s);
printf("\n%d ", count);//交換回数の出力
return 0;
}
I've been at this for an embarrassingly long time. And at this point I am adding more details just to make this post viable. It's been rough.
May I ask for some help, please?
You intialize s as s = a[i]; before initializing the array: this has undefined behavior. You should instead write:
s = rand() % NUM + 1;
Furthermore the shuffle function assumes the array has MAX elements whereas you define it with a length of NUM in main(). You should pass the length to shuffle().
Also note that x = (a[i] + a[j]) / 2 would have undefined behavior if the values in the array can be arbitrary large.
You should also consider adding some white space between the code and the comments to make the code more readable, especially to non Japanese readers.
Here is a modified version:
//CBinarysearch.c//
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define NUM 100
int binary_s(int a[], int n, int s) {
int lo, hi, mid;
int c = 0;
lo = 0; // loの初期化
hi = n - 1; // hiの初期化
while (lo <= hi) {
mid = lo + (hi - lo) / 2; // midの初期化
c++;
if (s == a[mid]) // 探索€¤がmidと同じ€¤となればloopを終了
break;
if (s > a[mid]) // 探索€¤がmidより大きい場合
lo = mid + 1; // loの€¤を;1してmidへ移動
else // 探索€¤がmidより小さい場合
hi = mid - 1; // hiの€¤をー1してmidへ移動
}
if (lo <= hi) {
printf("The numerical value %d is in array at index %d\n",
s, lo);
} else {
printf("value %d Could not be located in array.\n", s);
}
return c;
}
void shuffle(int a[], int len) {
int i, j;
int tmp;
for (i = len - 1; i > 0; i--) { // シャッフルのためのLoop
j = rand() % (i + 1); // jの€¤をラン€ム化
tmp = a[j];
a[j] = a[i];
a[i] = tmp;
}
}
void quicksort(int a[], int first, int last) {
int i, j, temp, x;
if (first >= last)
return;
i = first;
j = last;
x = ((long long)a[i] + a[j]) / 2; // 基準€¤は平均
while (1) {
while (a[i] < x) i++;
while (a[j] > x) j--;
//iがjより大きくなればwhile loopが解除される
if (i >= j) break;
//a[i]とa[j]を入れ替える
temp = a[i];
a[i] = a[j];
a[j] = temp;
i++;
j--;
}
quicksort(a, first, i - 1);
quicksort(a, j + 1, last);
}
int main(void) {
int a[NUM];
int i;
int count;
int s;
srand((unsigned int)time(NULL));
for (i = 0; i < NUM; i++) { // 整列数列の作成
a[i] = i + 1;
}
s = a[rand() % NUM];
shuffle(a, NUM); // Fisher-Yates shuffle
quicksort(a, 0, NUM - 1); // クイックソートの呼び出し
count = binary_s(a, NUM, s);
printf("iterations: %d\n", count); // 交換回数の出力
return 0;
}

Invalid results in merge sort application

Hello I am working on an application of the merge sort algorithm however after a few hours I am unable to find a solution. Any help or hint would be appreciated. I have tried to debug my code but after many attempts I have not been successful in seeing what the mistake is.
The problem is that the algorithm gives back a wrong result. Example:
input: (10, 5, 16, 2)
output: (2, 5, 5, 10)
#include <stdio.h>
void mergesort(int A[], int l, int r);
void merge(int A[], int l, int q, int r);
int main() {
int n;
scanf("%d", &n);
int tablica[n];
for (int i = 0; i < n; i++)
scanf("%d", &tablica[i]);
mergesort(tablica, 0, n - 1);
for (int i = 0; i < n; i++)
printf("%d ", tablica[i]);
return 0;
}
void mergesort(int A[], int l, int r) {
if (l < r) {
int q = (l + r) / 2;
mergesort(A, l, q);
mergesort(A, q + 1, r);
merge(A, l, q, r);
}
}
void merge(int A[], int l, int q, int r) {
int n = q - l + 1;
int m = r - q;
int B[n];
int C[m];
for (int i = 0; i < n; i++)
B[i] = A[i];
for (int i = 0; i < m; i++)
C[i] = A[q + 1 + i];
int i = 0;
int j = 0;
for (int k = l; k <= r; k++) {
if (B[i] <= C[j] || j >= m) {
A[k] = B[i];
i++;
} else {
A[k] = C[j];
j++;
}
}
}
Without knowing what exactly doesn't work (Does it not compile? Do you get wrong output for some inputs?) it's hard to help. At least one error is here:
if(B[i] <= C[j] || j >= m)
Should be
if(j >= m || i < n && B[i] <= C[j])
It is both important to check j >= m before you check the inequality, and add the i < n check.
Without the latter once you fully consume the B array, B[i] will go beyond the array boundaries, and you will get undefined behavior.
Without the former once j >= m the condition B[i] <= C[j] will be checked before j >= m, also triggering undefined behavior.
UPDATE: with the actual example you provided, the second error narrows down to replacing B[i] = A[i] with B[i] = A[l + i]. With these two changes the example you provided works.
The function merge has several bugs.
For example the size of the array C shall be calculated like
int m = r - q + 1;
instead of
int m = r - q;
Instead of this for loop
for(int i = 0; i < n; i++)
B[i] = A[i];
you have to write
for(int i = 0; i < n; i++)
B[i] = A[l + i];
This if statement
if(B[i] <= C[j] || j >= m)
can result in undefined behavior because there is no check of the validity of the used indices i and j whether they belong to the valid ranges.
The functions can be defined the following way as it is shown in the demonstrative program below.
#include <stdio.h>
void merge( int a[], size_t left, size_t middle, size_t right )
{
size_t n1 = middle - left;
size_t n2 = right - middle;
int a1[n1];
int a2[n2];
for ( size_t i = 0; i < n1; i++ )
{
a1[i] = a[left + i];
}
for ( size_t i = 0; i < n2; i++ )
{
a2[i] = a[middle + i];
}
size_t i = left, i1 = 0, i2 = 0;
while ( i1 < n1 && i2 < n2 )
{
a[i++] = a2[i2] < a1[i1] ? a2[i2++] : a1[i1++];
}
while ( i1 < n1 ) a[i++] = a1[i1++];
while ( i2 < n2 ) a[i++] = a2[i2++];
}
void mergesort( int a[], size_t left, size_t right )
{
if ( left + 1 < right )
{
size_t middle = ( left + right ) / 2;
mergesort( a, left, middle );
mergesort( a, middle, right );
merge( a, left, middle, right );
}
}
int main(void)
{
size_t n;
if ( scanf( "%zu", &n ) == 1 && n != 0 )
{
int a[n];
for ( size_t i = 0; i < n; i++ ) scanf( "%d", a + i );
mergesort( a, 0, n );
for ( size_t i = 0; i < n; i++ )
{
printf( "%d ", a[i] );
}
putchar( '\n' );
}
return 0;
}
If the input is
4
10 5 16 2
then the output will be
2 5 10 16
There is a bug in the merge function:
if (B[i] <= C[j] || j >= m) accesses B[i] and C[j] before testing if i and j are below their respective boundaries. The test should be:
if (i < n && (j >= m || B[i] <= C[j])) {
A[k] = B[i++];
} else {
A[k] = C[j++];
}
Note also these remarks:
you do not need to save the second half of the array because its elements are copied before they get overwritten.
in void mergesort(int A[], int l, int r) r should be excluded, to avoid confusing and error prone +1/-1 adjustments.
similarly, in void merge(int A[], int l, int q, int r), q should be the start of the second half and r the index of the element after the end of the slice.
l looks confusingly similar to 1
Here is a modified version:
#include <stdio.h>
void mergesort(int A[], int low, int high);
void merge(int A[], int low, int mid, int high);
int main() {
int n;
if (scanf("%d", &n) != 1 || n <= 0)
return 1;
int tablica[n];
for (int i = 0; i < n; i++) {
if (scanf("%d", &tablica[i]) != 1)
return 1;
}
mergesort(tablica, 0, n);
for (int i = 0; i < n; i++)
printf("%d ", tablica[i]);
printf("\n");
return 0;
}
void mergesort(int A[], int low, int high) {
if (high - low >= 2) {
int mid = low + (high - low) / 2;
mergesort(A, low, mid);
mergesort(A, mid, high);
merge(A, low, mid, high);
}
}
void merge(int A[], int low, int mid, int high) {
int n = mid - low;
int B[n];
for (int i = 0; i < n; i++)
B[i] = A[low + i];
int i = 0;
int j = mid;
int k = low;
while (i < n) {
if (j >= high || B[i] <= A[j]) {
A[k++] = B[i++];
} else {
A[k++] = C[j++];
}
}
}

Why variable "q" in quick-sort function equals 7 after first procedure (call)

I have implemented quicksort algorithm in C but I don't know how q and r work in quick_sort function. When the partitioning function returns i which is 1 it assigns this value to q but then for some reason, q becomes 7 and r becomes 0.
int partitioning(int A[10], int p, int r);
void quick_sort(int A[10], int p, int r);
int main() {
int A[10] = { 8, 7, 0, 20, 60, 5, 3, 7, 45, 1}, i;
for (i = 0; i <= 9; i++) {
printf(" %d ", A[i]);
}
printf("\n\nFinal Array\n\n");
quick_sort(A, 0, 9);
for (i = 0; i <= 9; i++) {
printf(" %d ", A[i]);
}
return 0;
}
int partitioning(int A[10], int p, int r) {
int tmp, i, x, j;
x = A[r];
i = p - 1;
for (j = p; j <= r; j++) {
if (A[j] < x) {
i++;
tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
}
i++;
tmp = A[i];
A[i] = A[r];
A[r] = tmp;
return i;
}
void quick_sort(int A[10], int p, int r) {
int q;
printf("%d\n", q);
if (p < r) {
q = partitioning(A, p, r);
quick_sort(A, p, q - 1);
quick_sort(A, q + 1, r);
}
}

Quicksort Depends on Choosing Pivot

This is my quicksort algorithm, including partition and swap. Works well, when I'm choosing as a pivot the last element of the array (in function quicksort: int r = partition(a, n, n);), but fails when taking the first: int r = partition(a, n, s);
void Swap(int a[], int l, int r){
int tmp = a[l];
a[l] = a[r];
a[r] = tmp;
}
int partition(int a[], int n, int p) {
Swap(a, p, n);
int l = 0;
for (int i = 1; i <= n - 1; i++) {
if (a[i] <= a[n]) {
l += 1;
Swap(a, l, i);
}
}
Swap(a, p, l + 1);
return l + 1;
}
void quicksort(int a[], int s, int n) {
if (s < n) {
int r = partition(a, n, n);
quicksort(a, s, r - 1);
quicksort(a, r + 1, n);
}
}
Yes, the problem was with the partition procedure, this one is correct:
int partition(int a[], int p, int r) {
int t = a[r];
int i = p - 1;
for (int j = p; j < r;j++){
if (a[j] <= t) {
i += 1;
std::swap(a[i], a[j]);
}
}
std::swap(a[i + 1], a[r]);
return i + 1;
}

Merge Sort Error : Segmentation Fault

I'm getting an error Segmentation Fault:11, please help.
variable info:(s:start, e:end, m:mid, n:array), testing for a sample array n[] = {4,3,2,1}. a1 and a2 are temporary arrays. I am guessing there's something with the calculation of m:mid and passing it.
#include <stdio.h>
void merge(int s, int e, int m, int n[]) {
int l1 = m - s;
int l2 = e - m + 1;
int a1[l1];
int a2[l2];
for (int i = 0; i < l1; i++) {
a1[i] = n[s + i];
}
for (int j = 0; j < l2; j++) {
a2[j] = n[s + m + j];
}
int i = 0, j = 0;
for (int k = 0; k < l1 + l2; k++) {
if (a1[i] <= a2[j] && i != l1 && j != l2) {
n[k] = a1[i];
i++;
} else if (a2[j] <= a1[i] && i != l1 && j != l2) {
n[k] = a2[j];
j++;
} else if (j == l2 && i != l1) {
n[k] = a1[i];
i++;
} else if(i == l1 && j != l2) {
n[k] = a2[j];
j++;
}
}
}
void mergeSort(int s, int e, int n[]) {
if (s < e) {
int m = (e - s) / 2;
mergeSort(s, m - 1, n);
mergeSort(m, e, n);
merge(s, e, m, n);
}
}
int main(void) {
int n[] = { 4, 3, 2, 1 };
int r = 4;
mergeSort(0, r - 1, n);
for(int i = 0; i < r; i++) {
printf("%i\n", n[i]);
}
}
The computation of m for the middle element is bogus: you get the offset of m from s, not its index into the array.
Here is a corrected version:
void mergeSort(int s, int e, int n[]) {
if (s < e) {
int m = s + (e - s + 1) / 2;
mergeSort(s, m - 1, n);
mergeSort(m, e, n);
merge(s, e, m, n);
}
}
There are other issues in your code, notably:
you should check the offsets i and j beforedereferencinga1[i]anda2[j]`.
the offset k should not be used directly in the merge phase, you should store to n[s + k].
in the initialization loop for a2, you should use a2[j] = n[m + j]; instead of a2[j] = n[s + m + j];
Note also that it is idiomatic to pass ranges in C with the first index included and the last index excluded. This allows for passing empty ranges, which your current method does not. It also makes the code much simpler and easier to read.
Here is a modified version:
#include <stdio.h>
void merge(int s, int e, int m, int n[]) {
int l1 = m - s;
int l2 = e - m;
int a1[l1];
int a2[l2];
for (int i = 0; i < l1; i++) {
a1[i] = n[s + i];
}
for (int j = 0; j < l2; j++) {
a2[j] = n[m + j];
}
for (int i = 0, j = 0, k = 0; k < l1 + l2; k++) {
if (i < l1 && (j >= l2 || a1[i] <= a2[j])) {
n[s + k] = a1[i];
i++;
} else {
n[s + k] = a2[j];
j++;
}
}
}
void mergeSort(int s, int e, int n[]) {
if (e > s + 1) {
int m = s + (e - s) / 2;
mergeSort(s, m, n);
mergeSort(m, e, n);
merge(s, e, m, n);
}
}
int main(void) {
int n[] = { 4, 3, 2, 1 };
int r = sizeof(n) / sizeof(n[0]);
mergeSort(0, r, n);
for(int i = 0; i < r; i++) {
printf("%i\n", n[i]);
}
return 0;
}
I've modified your code in several places. Try to use your debugger or pen & paper to understand what's going on under the hood.
void merge(int s, int e, int m, int n[]){
int l1 = m-s + 1;
int l2 = e - m;
int a1[l1];
int a2[l2];
for(int i = 0; i < l1; i++){
a1[i] = n[s+i];
}
for(int j = 0; j < l2; j++){
a2[j] = n[m+j + 1];
}
int i = 0, j = 0;
for(int k = 0; k < l1+l2; k++){
if(a1[i] <= a2[j] && i != l1 && j != l2){
n[k] = a1[i];
i++;
}else if(a2[j] <= a1[i] && i != l1 && j != l2){
n[k] = a2[j];
j++;
}else if(j == l2 && i != l1){
n[k] = a1[i];
i++;
}else if(i == l1 && j != l2){
n[k] = a2[j];
j++;
}
}
}
void mergeSort(int s, int e, int n[]){
if(s<e){
int m = s + (e-s)/2;
mergeSort(s, m, n);
mergeSort(m + 1, e, n);
merge(s,e,m, n);
}
You will be fine I guess.
I think you have a stack overflow problem because of infinite recursive calls. Look
void mergeSort(int s, int e, int n[]){
if(s<e){
int m = (e-s)/2;
mergeSort(s, m-1, n);
mergeSort(m, e, n);
merge(s,e,m, n);
}
}
You pass these values of s and e:
s e function
-------------
0 3 mergeSort
0 0 mergeSort -> end
1 3 mergeSort
0 0 mergeSort -> end
1 3 mergeSort
... (infinite calls)
Then the stack grows and grows while new functions called until in the end it exceeds the maximum possible size, which leads to SEGFAULT.

Resources