本文介绍了简单的冒泡排序 C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
int[] arr = {800,11,50,771,649,770,240, 9};
int temp = 0;
for (int write = 0; write < arr.Length; write++)
{
for (int sort = 0; sort < arr.Length - 1; sort++)
{
if (arr[sort] > arr[sort + 1])
{
temp = arr[sort + 1];
arr[sort + 1] = arr[sort];
arr[sort] = temp;
}
}
Console.Write("{0} ", arr[write]);
}
我试图做的只是对这个数组进行简单的冒泡排序.我想弄清楚为什么排序会搞砸.例如,当数组为 {800,11,50,771,649,770,240, 9}
时:
All I am attempting to do is a simple bubble sort with this array. I would like to figure out why the sorting is screwed up.In example, here is when the array is {800,11,50,771,649,770,240, 9}
:
这是显示的内容:11, 50, 649, 9, 649, 770, 771, 800
我想我可能在比较中遗漏了一些东西.
I am thinking that I might be missing something in the comparison.
推荐答案
不,您的算法有效,但您的 Write
操作在外循环中放错了位置.
No, your algorithm works but your Write
operation is misplaced within the outer loop.
int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };
int temp = 0;
for (int write = 0; write < arr.Length; write++) {
for (int sort = 0; sort < arr.Length - 1; sort++) {
if (arr[sort] > arr[sort + 1]) {
temp = arr[sort + 1];
arr[sort + 1] = arr[sort];
arr[sort] = temp;
}
}
}
for (int i = 0; i < arr.Length; i++)
Console.Write(arr[i] + " ");
Console.ReadKey();
这篇关于简单的冒泡排序 C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!