[C Language] Shift the elements after sorting the elements of an array

[C Language] Shift the elements after sorting the elements of an array

1. Topic

Xiaoke likes to study arrays recently, and he discovered a new problem: how to sort the elements of an array and then shift the elements?

Set the given original array as: 4 2 3 1 5 8 7 10 6 9

Enter 1 first, then sort in ascending order 1 2 3 4 5 6 7 8 9 10

Then enter 3, then the first 3 elements will be translated to the back of the array, and the final array elements will be 4 5 6 7 8 9 10 1 2 3

Example 1:

Input:
1
3
Output:
1 2 3 4 5 6 7 8 9 10
4 5 6 7 8 9 10 1 2 3

Example 2:

Input:
2
5
Output:
10 9 8 7 6 5 4 3 2 1
5 4 3 2 1 10 9 8 7 6

2. Complete code

#define _CRT_SECURE_NO_WARNINGS  // Visual Studio版本太新需加上
#include <stdio.h>

// 升序
int Increase(int a[], int n) {
    
    
	for (int i = 0; i < n - 1; i++)
	{
    
    
		if (a[i] > a[i + 1])
		{
    
    
			int temp;
			temp = a[i];
			a[i] = a[i + 1];
			a[i + 1] = temp;
		}
	}
	return a;
}

// 降序
int Reduce(int a[], int n) {
    
    
	for (int i = 0; i < n - 1; i++)
		for (int j = 0; j < n - 1 - i; j++)
			if (a[j] < a[j + 1])
			{
    
    
				int temp;
				temp = a[j];
				a[j] = a[j + 1];
				a[j + 1] = temp;
			}
	return a;
}

// 位移
int MoveElements(int a[], int n, int k)
{
    
    
	for (int i = 0; i < k; i++)
	{
    
    
		int m = k - 1 - i;
		int j = m + 1;
		while (j < n - i)
		{
    
    
			a[m] += a[j];
			a[j] = a[m] - a[j];
			a[m] -= a[j];
			m++;
			j++;
		}
	}
	return a;
}

int main() {
    
    
	int a, b, i, j;
	int x[] = {
    
     4 ,2 ,3 ,1 ,5 ,8 ,7 ,10, 6, 9 };
	scanf("%d", &a);
	if (a == 1) {
    
    
		for (j = 10; j >= 1; j--)
		{
    
    
			Increase(x, 10);
		}
		for (i = 0; i < 10; i++)
		{
    
    
			printf("%d ", x[i]);
		}
		printf("\n");
	}
	else if (a == 2) {
    
    
		Reduce(x, 10);
		for (i = 0; i < 10; i++) {
    
    
			printf("%d ", x[i]);
		}
		printf("\n");
	}
	scanf("%d", &b);
	MoveElements(x, 10, b);
	for (i = 0; i < 10; i++)
	{
    
    
		printf("%d ", x[i]);
	}
}

3. Screenshot

insert image description here
insert image description here

おすすめ

転載: blog.csdn.net/a6661314/article/details/125075232