tema
Hay una matriz de enteros distintos de cero A [n], intente escribir un algoritmo para poner los enteros menores que 0 en A antes de A, y coloque los enteros mayores que 0 detrás de A. Se requiere no usar otras estructuras de datos auxiliares !
análisis
Colocamos dos banderas, i y j. i es el elemento principal, j es un elemento determinado. ¡Déjalos atravesar desde ambos extremos hasta el medio! Cuando i> = j, ¡el ciclo termina! Dentro de este bucle se divide en cuatro ramas seleccionadas se determina cuando a[i] > 0 && a[j] > 0
j se mueve hacia adelante, yo no me muevo; cuando a[i] > 0 && a[j] < 0
, la posición de los dos elementos a intercambiar, y i ++, j-; cuando a[i] < 0 && a[j]>0
, la posición de los dos elementos para ser intercambiado, Y i ++, j–; cuando a[i] < 0 && a[j] < 0
i ++;
Código
void Rearrange(int a[], int n) {
int i = 0; //{-1,2,3,-5,0,1}
int j = 4; //{-1,-5,3}
int temp;
while (i < j) {
if (a[i] > 0 && a[j] > 0) {
j--;
}
else if (a[i] > 0 && a[j] < 0) {
temp = a[j];
a[j] = a[i];
a[i] = temp;
i++;
j--;
}
else if (a[i] < 0 && a[j]>0) {
temp = a[j];
a[j] = a[i];
a[i] = temp;
i++;
j--;
}
else if (a[i] < 0 && a[j] < 0) {
i++;
}
}
}
prueba
// ConsoleApplication6.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include "pch.h"
#include <iostream>
void Rearrange(int a[], int n) {
int i = 0; //{-1,2,3,-5,0,1}
int j = 4; //{-1,-5,3}
int temp;
while (i < j) {
if (a[i] > 0 && a[j] > 0) {
j--;
}
else if (a[i] > 0 && a[j] < 0) {
temp = a[j];
a[j] = a[i];
a[i] = temp;
i++;
j--;
}
else if (a[i] < 0 && a[j]>0) {
temp = a[j];
a[j] = a[i];
a[i] = temp;
i++;
j--;
}
else if (a[i] < 0 && a[j] < 0) {
i++;
}
}
}
int main()
{
int a[] = {
1,2,3,-5,-1 }; //{-1,2,3,-5,0,1}
Rearrange(a, 5);
for (int i = 0; i <= 4; i++) {
printf("%d\n", a[i]);
}
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门提示:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件