while (true) { int.TryParse(Console.ReadLine(), out int N); int[] arr = new int[N]; Random ran = new Random(); for (int i = 0; i < arr.Length; i++) { arr[i] = ran.Next(1, 1000); } Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); Sort(arr); Console.WriteLine($"第{N / 2}大的數爲:" + arr[N / 2 - 1]); stopwatch.Stop(); TimeSpan tp = stopwatch.Elapsed; Console.WriteLine($"程序運行:總毫秒:{tp.TotalMilliseconds}"); } //從大到小 static int[] Sort(int[] arr) { int temp; for (int i = 0; i < arr.Length - 1; i++) { for (int j = i + 1; j < arr.Length; j++) { if (arr[i] < arr[j]) { temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } return arr; }
用最簡單的數組索引返回k最大值,時間複雜度慘不忍睹。數組