题解 | #有序序列判断#
有序序列判断
https://www.nowcoder.com/practice/22e87f8a8d764a6582710f38d1b40c6e
思路:对于此题我的思路是用冒泡排序的思维先创建计数器,把输入的数字排序,如果冒泡排序交换的次数是0,那就是顺序;如果是n-1的从1到n-1的和,即n*(n-1)/2,那就是逆序,除了这两种情况是有序排列,其他的都是无序排列。
int main()
{
int count = 0;
int n = 0;
int arr[10000] = { 0 };
scanf("%d", &n);
int i = 0;
for (i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
for (i = 0; i < n-1; i++)
{
int j = 0;
for (j = 0; j < n-1 - i; j++)
{
if (arr[j] > arr[j + 1])
{
count++;
int tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
}
}
}
int ret = n*(n-1) / 2;
if (count == 0 || count == ret)
printf("sorted\n");
else
printf("unsorted\n");
return 0;
}
{
int count = 0;
int n = 0;
int arr[10000] = { 0 };
scanf("%d", &n);
int i = 0;
for (i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
for (i = 0; i < n-1; i++)
{
int j = 0;
for (j = 0; j < n-1 - i; j++)
{
if (arr[j] > arr[j + 1])
{
count++;
int tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
}
}
}
int ret = n*(n-1) / 2;
if (count == 0 || count == ret)
printf("sorted\n");
else
printf("unsorted\n");
return 0;
}