开发者

How to sort numbers

开发者 https://www.devze.com 2022-12-27 06:15 出处:网络
I need some help to be able to handle the following logic. The program gets many integers input like 10,16,3,17,21,29,6.

I need some help to be able to handle the following logic. The program gets many integers input like 10,16,3,17,21,29,6.

Logic to be done:

Scenario 1:

Firs开发者_开发技巧t select the biggest 4 numbers of input which is 16,17,21,29. Now assign the values to A,B,C and D:

  • A = smallest in the selected 4
  • B = biggest in the selected 4
  • C = second smallest in the selected 4
  • D = third smallest in the selected 4

Result to be Displayed:

A = 16
B = 29
C = 17
D = 21

Scenario: 2

If the user gives 3 inputs like 3,6,10 assign only to A,B,C and should ignore D

Result to be Displayed:

A = 3
B = 10
C = 6


Assuming that you have your input values in an array, you can sort it using the static Array.Sort() method and then pick the top/bottom ones by indexing (eg. values[value.Length - 1] gets the highest value). Do make sure to do some bounds checking to avoid runtime exceptions, and to solve "scenario 2" of the assignment correctly.

If you want something more modern, you could also use some LINQ magic to get the top 4 items:

values = values.OrderByDescending(i => i).Take(4).ToArray();

The four highest values are now in highOnes for you to print in whatever order you please. Once again, make sure to do some bounds checking - there might be less than four numbers in the array.


I would take the input and store them into a List. I would then sort this list. Once sorted you can then pull out the numbers as required.


Logic:

  1. Sort in descending order
  2. Select top 4 element
  3. Assign value as per your requirement in A,B,C,D


Sounds like this could be an assignment so I'll give you these tips:

If you have all these numbers in an array, you can try partially sorting the array. Write a simple bubble sort, and have it sort the largest numbers to the front. But instead of sorting the whole array, make it stop after it brings the 4 largest elements to the front of the array.

That way, your first element will be your largest, and so forth. From there, you can do the rest of the things you need easily.

Hope that helped.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号