![](/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.