![](/img/trans.png)
[英]Is there any performance issue using comments in the loop in java, javascript, and c#?
[英]c# method to sort array without using any loop
我们如何编写 c-sharp 方法或 java 方法来在不使用任何循环的情况下对数组进行排序,我尝试了以下操作但无法正常工作。
public static void sortArray(int[] array)
{
int index = 0;
int temp = 0;
if (index < array.Length - 1)
{
if (array[index] > array[index + 1])
{
temp = array[index];
array[index] = array[index + 1];
array[index + 1] = temp;
}
index++;
sortArray(array, index);
}
}
解决方案有点棘手,但它终于奏效了。
C#代码:
public static void sortArray(int[] array, int index)
{
if (index < array.Length - 1)
{
if (array[index] > array[index + 1])
{
var temp = array[index];
array[index] = array[index + 1];
array[index + 1] = temp;
}
if (index > 0 && array[index] < array[index - 1]) sortArray(array, index - 1);
else sortArray(array, index + 1);
}
}
用法:
int[] arr = { 3000, 2000, 1000, 800, 100, 500, 200, 6, 8, 7, 17, 78, 22, };
sortArray(arr, 0);
此方法就地对数组进行排序,因此arr
本身将被排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.