且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

按升序对数组进行排序

更新时间:2022-11-16 12:02:41

这是你的作业,但是...这是一种奇怪的排序算法。

我这样做的方式(好吧,如果我必须写一个基本的排序算法)就是做一个冒泡排序:冒泡排序 - *** [ ^ ]

你们不这样做 - 它有点停止,所以输出顺序有点奇怪。 br />
但它很容易解决!只需改变这个:

 for(int k = j + 1; k< arrayLength  -  1; k ++)

对此:

 for(int k = j + 1; k< arrayLength; k ++)


它被称为冒泡排序 ,现在你知道它叫做什么你可以google了,有很多文章解释它的动画



算法第1课:Bubblesort - *** [ ^ ]


您可以使用 Linq

使用系统; 
使用System.Collections.Generic;
使用System.Linq;

公共课程
{
public static void Main()
{
List< int> li = new List< int>();
li.Add(1);
li.Add(2);

var lidesc = li.OrderByDescending(i => i);


foreach(l l中的var l)
{
Console.WriteLine(number+ l);
}
}
}


I'm very new to coding and have been staring at this bit of code for hours...

I understand how the parameters in the for statement work when just printing out a range of numbers to the console but in this example it is sorting the values in ascending order.

To me the parameters look very similar, I can see that they're different but it does look as though it is using the same principle. I was just hoping someone could explain how this actually sorts the array into ascending order, I cannot work it out.

What I have tried:

 const int arrayLength = 5;
           int[] sortArray = new int[arrayLength];
           for (int i = 0; i < arrayLength; i++)
           {
               Console.WriteLine("Enter value: ");
               sortArray[i] = Convert.ToInt32(Console.ReadLine());
           }

           Console.WriteLine("Now sort it: ");
           for (int j = 0; j < arrayLength; j++)
           {
               for (int k = j + 1; k < arrayLength - 1; k++)
               {
                   if (sortArray[j] > sortArray[k])
                   {
                       int big = sortArray[j];
                       sortArray[j] = sortArray[k];
                       sortArray[k] = big;
}
               }
           }

           Console.WriteLine("Now print it: ");
           for (int l = 0; l < sortArray.Length; l++)
           {
               Console.WriteLine(sortArray[l]);
           }


This is your homework, but ... that's an odd sort algorithm.
The way I'd do it (well, if I had to write a basic sort algorithm) would be to do a bubble sort: Bubble sort - Wikipedia[^]
Yours doesn't do that - it kinda stops too early, so the output order is a little odd.
But it's easy to solve! Just change this:
for (int k = j + 1; k < arrayLength - 1; k++)

To this:

for (int k = j + 1; k < arrayLength; k++)


It's called a "bubble sort", now you know what it's called you can google for it, there are plenty of articles\animations that explain it

Algorithms Lesson 1: Bubblesort - ***[^]


You can use Linq:
using System;
using System.Collections.Generic;
using System.Linq;
					
public class Program
{
	public static void Main()
	{
		List<int> li = new List<int>();
		li.Add(1);
		li.Add(2);
		
		var lidesc = li.OrderByDescending(i => i);
		
		
		foreach (var l in lidesc)
		{
			Console.WriteLine("number " + l);
		}
	}
}