R
R
Retr0Hacker2021-12-05 20:17:50
C++ / C#
Retr0Hacker, 2021-12-05 20:17:50

How to do shell sort in C?

Initially, the task was simply to write a program for sorting entered (or randomly generated) numbers using the Shell method. But then the teacher decided to complicate the task and said:

"Create another function that will test the Shell algorithm: create a set of arrays of n random numbers, sort according to the Shell method and display the average number of iterations for all these arrays"

I got everything except the average value for all arrays
Tell me how can I do this

This is my code:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void shellsort(int v[], int n);

int main() {
  int SIZE;
  printf("Input SIZE: ");
  scanf_s("%d", &SIZE);
  int N;
  printf("Input N: ");
  scanf_s("%d", &N);
  int* a = (int*)malloc(SIZE * sizeof(int));
  int i = 0, num = 0;

  while (num != N) {
    printf("-------------------------------");
    printf("\n");
    printf("Enter masiv: ");
    for (i = 0; i < SIZE; i++) {
      a[i] = rand() % 100;
      printf("%d ", a[i]);
    }

    shellsort(a, SIZE);

    printf("\n");
    printf("Result: ");
    for (i = 0; i < SIZE; i++) {
      printf("%d ", a[i]);
    }
    printf("\n");
    num++;
  }

  return 0;
}

void shellsort(int v[], int n) {

  int k, i, j, gap, temp;
  int iterations = 0;

  for (gap = n / 2; gap > 0; gap /= 2) {
    for (i = gap; i < n; i++) {
      for (j = i - gap; j >= 0 && v[j] > v[j + gap]; j -= gap)
      {
        temp = v[j];
        v[j] = v[j + gap];
        v[j + gap] = temp;
        iterations++;
      }
    }
  }
  printf("\n");
  printf("Number of iterations: %d\n", iterations);
}


Thanks in advance to everyone who responds!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
res2001, 2021-12-06
@res2001

Return iterations from shellsort. In main, sum these values ​​and find the average at the end.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question