I am trying to solve my task using a List and I know I am very close to solving it but I am stuck now. Something is not ok in the code and I can not figure out what it is. Could you please take a look and help:
/*
Write a program that reads an array of integers and removes from it a minimal number of elements in such way that the
remaining array is sorted in increasing order. Print the remaining sorted array.
Example: {6, 1, 4, 3, 0, 3, 6, 4, 5} {1, 3, 3, 4, 5}
*/
using System;
using System.Collections.Generic;
class RemoveMinimalElements
{
static void Main()
{
int n;
n = int.Parse(Console.ReadLine());
List<int> arr = new List<int>();
List<int> sorted = new List<int>();
int maxSubsetLenght = 0;
for (int i = 0; i < n; i++)
{
arr.Add(int.Parse(Console.ReadLine()));
}
for (int i = 1; i <= (int)Math.Pow(2, n) - 1; i++)
{
int tempSubsetLenght = 0;
string tempString = "";
List<int> temp = new List<int>();
for (int j = 1; j <= n; j++)
{
int andMask = i & (1 << j);
int bit = andMask >> j;
if (bit == 1)
{
temp.Add(arr[n - 1 - j]);
tempSubsetLenght++;
}
if (tempSubsetLenght > maxSubsetLenght)
{
maxSubsetLenght = tempSubsetLenght;
for(int k =1; k < temp.Count; k ++)
{
if (temp[k] >= temp[k - 1])
{
sorted = temp;
}
}
}
}
}
for (int i = sorted.Count - 1; i > 0; i--)
{
Console.WriteLine(sorted[i]);
}
}
}
I didn't follow the code, I just tested your app.
This is my first input: 5.
Then I entered these 5 inputs 2,4,6,8,10 so
arr = {2,4,6,8,10};
And when it came to the last lines it gave me the ArguementOutOfRangeException (Index was out of range. Must be non-negative and less than the size of the collection.) because it was trying to fetch arr[item] and item is 6 so it's trying to fetch arr[6] which does not exist.
I don't know if an exhaustive search is suitable for your case, but will this work for you?
static void Main(string[] args)
{
int[] input = new[] { 6, 1, 4, 3, 0, 3, 6, 4, 5 };
int[] expectedOutput = new[] { 1, 3, 3, 4, 5 };
int[] solution = TryGetSolution(input);
Console.WriteLine("Input: " + FormatNumbers(input));
Console.WriteLine("Expected Output: " + FormatNumbers(expectedOutput));
Console.WriteLine("Output: " + FormatNumbers(solution));
Console.ReadLine();
}
private static string FormatNumbers(int[] numbers)
{
return string.Join(", ", numbers);
}
private static int[] TryGetSolution(int[] input)
{
return TryWithoutAnyItem(input);
}
private static int[] TryWithoutAnyItem(int[] items)
{
return Enumerable.Range(0, items.Length)
.Select(i => TryWithoutItem(items, i))
.Where(solution => solution != null)
.OrderByDescending(solution => solution.Length)
.FirstOrDefault();
}
private static int[] TryWithoutItem(int[] items, int withoutIndex)
{
if (IsSorted(items)) return items;
var removed = items.Take(withoutIndex).Concat(items.Skip(withoutIndex + 1));
return TryWithoutAnyItem(removed.ToArray());
}
private static bool IsSorted(IEnumerable<int> items)
{
return items.Zip(items.Skip(1), (a, b) => a.CompareTo(b)).All(c => c <= 0);
}
}
I solved it! Thank you very much for your support. I am a beginer and I am not able to use and understand more difficult stuff yet so here is what I did whit the things I already know:
/*
Write a program that reads an array of integers and removes from it a minimal number of elements in such way that the
remaining array is sorted in increasing order. Print the remaining sorted array.
Example: {6, 1, 4, 3, 0, 3, 6, 4, 5} {1, 3, 3, 4, 5}
*/
using System;
using System.Collections.Generic;
class RemoveMinimalElements
{
static bool CheckAscending(List<int> list)
{
bool ascending = true;
for (int i = 0; i < list.Count - 1; i++)
{
if (list[i] > list[i + 1])
{
ascending = false;
}
}
return ascending;
}
static void Main()
{
int n;
n = int.Parse(Console.ReadLine());
List<int> arr = new List<int>();
List<int> sorted = new List<int>();
int maxSubsetLenght = 0;
for (int i = 0; i < n; i++)
{
arr.Add(int.Parse(Console.ReadLine()));
}
for (int i = 1; i <= (int)Math.Pow(2, n) - 1; i++)
{
int tempSubsetLenght = 0;
List<int> temp = new List<int>();
for (int j = 1; j <= n; j++)
{
if (((i >> (j - 1)) & 1) == 1)
{
temp.Add(arr[j - 1]);
tempSubsetLenght++;
}
}
if ((tempSubsetLenght > maxSubsetLenght) && (CheckAscending(temp)))
{
sorted = temp;
maxSubsetLenght = tempSubsetLenght;
}
}
for (int i = 0; i < sorted.Count; i++)
{
Console.WriteLine(sorted[i]);
}
}
}
This works for me
private static void FindLongestRisingSequence(int[] inputArray)
{
int[] array = inputArray;
List<int> list = new List<int>();
List<int> longestList = new List<int>();
int highestCount = 1;
for (int i = 0; i < array.Length; i++)
{
list.Add(array[i]);
for (int j = i+1; j < array.Length; j++)
{
if (array[i] < array[j])
{
list.Add(array[j]);
i++;
}
else
{
break;
}
i = j;
}
// Compare with in previous lists
if (highestCount < list.Count)
{
highestCount = list.Count;
longestList = new List<int>(list);
}
list.Clear();
}
Console.WriteLine();
// Print list
Console.WriteLine("The longest subsequence");
foreach (int iterator in longestList)
{
Console.Write(iterator + " ");
}
Console.WriteLine();
}
Related
this is the problem [enter image description here][1]
class Program
{
/* I 'am sorry, but if written this code in french so I will explain the name of variables in English, and what are they doing
and Yes I am aware this code is spaghetti and I would appreciate if there is a better way to write it
T is an Array, and cible is a target */
public static int [] getRange(int[] T, int cible)
{
// T_indices is an Array of indexes
int[] T_indices = new int[10];
//cpt is a counting variable
int cpt=0;
for (int i = 0; i < T.Length; i++)
{
if(T[i]==cible)
{
for (int j = i; j < T.Length; j++)
{
if(T[i]==T[j])
{
T_indices[cpt] = j;
cpt++;
}
else
{
break;
}
}
break;
}
}
//checking if the element doesn't existe so we can return a -1
if(cpt==0)
{
T_indices = new int[1];
T_indices[0] = -1;
return T_indices;
}
else
{
//T_indices_Finaux is the final index Array
int[] T_indices_Finaux = new int[2];
T_indices_Finaux[0] = T_indices[0];
// Max doesn't need explanation I guess
int max = T_indices[0];
for (int i = 0; i < T_indices.Length; i++)
{
if(max< T_indices[i])
{
max = T_indices[i];
}
}
T_indices_Finaux[1] = max;
if(T_indices_Finaux[0]== T_indices_Finaux[1])
{
T_indices_Finaux = new int[1];
T_indices_Finaux[0] = T_indices[0];
}
return T_indices_Finaux;
}
}
// here we put this spaghetti code to the test suprisenly wroking out
static void Main(string[] args)
{
int[] T = { 1, 2, 2, 2, 2, 3, 4, 7, 8, 8 };
for (int i = 0; i < getRange(T, 2).Length; i++)
{
Console.WriteLine(getRange(T, 2)[i]);
}
Console.Read();
}
}
int[] T_indices = new int[10];
How do you know, that 10 is enough? You do not. This magic number would cause, that the code sometimes works and sometimes it just throws out of range exception. Besides this, the code is okay, but you do it in a bit too complicated way. What you need is basically this
public static int[] getRange(int[] T, int cible)
{
for (int i = 0; i < T.Length; ++i)
{
if (T[i] == cible)
{
int j = i + 1;
while (j < T.Length && T[j] == cible) { ++j; }
--j;
if (i == j) { return new int[] { i }; }
return new int[] { i, j };
}
}
return new int[] { -1 };
}
And btw. the test code calls the getRange function up to three times. You should call it once, store the result array and loop over that array.
pleas try this :
change getRange Method to this :
public static List<int> getRange(int[] T, int cible)
{
var result=new List<int>();
var list = T.ToList();
if(!list.Contains(cible))
result.Add(-1);
else
{
result.Add(list.IndexOf(cible));
if (list.Count(x=>x==cible)>1)
result.Add(list.LastIndexOf(cible));
}
return result;
}
and use it like this :
int[] T = { 1, 2, 2, 2, 2, 3, 4, 7, 8, 8 };
getRange(T, 2).ForEach(Console.WriteLine);
In this solution you will never get an OutOfRange ٍException and also use the native c # method (for get index of a item in array. "IndexOf" Instead "for") which is much faster and more efficient.
So I am trying to solve this task "Digit Difference Sort" on Codefights
Given an array of integers, sort its elements by the difference of their largest and smallest digits.
In the case of a tie, that with the larger index in the array should come first.
Example
For a = [152, 23, 7, 887, 243], the output should be digitDifferenceSort(a) = [7, 887, 23, 243, 152].
Here are the differences of all the numbers:
152: difference = 5 - 1 = 4;
23: difference = 3 - 2 = 1;
7: difference = 7 - 7 = 0;
887: difference = 8 - 7 = 1;
243: difference = 4 - 2 = 2.
23 and 887 have the same difference, but 887 goes after 23 in a, so in the sorted array it comes first.
I have an issue with two numbers having the same difference. Here's what I wrote so far:
int[] digitDifferenceSort(int[] a) {
return a.OrderBy(x => difference(x)).ToArray();
}
int difference(int x)
{
int min = 9, max = 0;
do
{
int tmp = x % 10;
min = Math.Min(min, tmp);
max = Math.Max(max, tmp);
} while ((x /= 10) > 0);
return max - min;
}
Didn't do much (for example the output is still [7, 23, 887, 243, 152] rather than [7, 887, 23, 243, 152])
How do I make element with larger index come first in result? What should I use instead of OrderBy?
I don't consider your difference method, i assume it works fine.
To your question: you have to keep revered order of the array (that the items with the same difference arrive will be sorted reverse). To do it, you could just reverse you input array: all items with not identical difference will be ordered correctly, and with the same differece will be ordered reversed:
int[] digitDifferenceSort(int[] a)
{
return a.Reverse().OrderBy(x => difference(x)).ToArray();
}
Following is my code for the above question digit difference sort. I am also getting output when running in Eclipse but when I paste the code on code signal it gives me a null pointer exception.
package NormalPrograms;
import java.util.ArrayList;
import java.util.Collections;
public class DigitDifferenceSort {
// For index wise sorting in descending order
public static int[] sortingnumberindexwise(int[] a, ArrayList<Integer> index) {
int k = 0;
int[] res = new int[index.size()];
int[] finalres = new int[index.size()];
for (int i = a.length - 1; i >= 0; i--) {
for (int j = 0; j < index.size(); j++) {
if (a[i] == (int) index.get(j)) {
res[k] = i;
index.remove(j);
k++;
break;
}
}
}
int g = 0;
k = 0;
for (int i = 0; i < res.length; i++) {
finalres[g] = a[res[k]];
g++;
k++;
}
return finalres;
}
public static int[] finddigitDifferenceandSort(int[] p) {
int[] finres = new int[p.length];
for (int i = 0; i < finres.length; i++) {
finres[i] = p[i];
}
// This finres array act as an temp array and reused to make final result array
int digit = 0;
ArrayList<Integer> A = new ArrayList<Integer>();
ArrayList<ArrayList<Integer>> B = new ArrayList<ArrayList<Integer>>();
for (int i = 0; i < 10; i++) {
B.add(new ArrayList<Integer>());
}
for (int i = 0; i < p.length; i++) {
int temp = 0;
temp = p[i];
while (p[i] > 0) {
digit = p[i] % 10;
p[i] /= 10;
A.add(digit);
}
int b = Collections.max(A);
int c = Collections.min(A);
int diff = b - c;
B.get(diff).add(temp);
A.clear();
}
for (int i = 0; i < B.size(); i++) {
if (B.get(i).size() > 1) {
ArrayList<Integer> C = new ArrayList<Integer>();
for (int k = 0; k < B.get(i).size(); k++) {
C.add(B.get(i).get(k));
}
B.get(i).clear();
for (int j : sortingnumberindexwise(finres, C)) {
B.get(i).add(j);
}
} else {
continue;
}
}
int k = 0;
for (int i = 0; i < B.size(); i++) {
for (int j = 0; j < B.get(i).size(); j++) {
if (B.get(i).size() == 0)
continue;
else {
finres[k] = B.get(i).get(j);
k++;
}
}
}
return finres;
}
public static void main(String[] args) {
int[] a = { 12, 21, 1, 1, 1, 2, 2, 3 };
for (int i : finddigitDifferenceandSort(a)) {
System.out.print(i + " ");
}
}
}
I am trying to practice some c# questions and I came across a question where given an integer of array, return the array with elements that can be repeated only N times. So, if I have {1,2,3,4,1,1,2,3} and my N=2, my result should be {1,2,3,4,1,2,3}. I tried something but I get the result as {2,3,4,1,1,2,3}.I don't want the first repeated element be removed.
This is what I have tried :
int[] intArray = {3,2,3,1,3};
int N = 2;
var list = new List<int>(intArray);
var newList = new List<int>();
for (int i = 0; i < list.Count; i++)
{
int occur = 1;
for (int j = i+1; j < list.Count; j++)
{
if (occur < N && list[i] == list[j])
{
occur++;
newList.Add(list[j]);
}
else
{
if (list[i] == list[j] )
list.Remove(list[j]);
}
}
}
foreach (var l in list)
{
Console.WriteLine(l);
}
}
}
I would really appreciate any help or guidance.
I suggest using Dictionary<T, int> to count appearances:
private static IEnumerable<T> RepeatOnly<T>(IEnumerable<T> source, int times) {
Dictionary<T, int> counts = new Dictionary<T, int>();
foreach (var item in source) {
int count;
if (counts.TryGetValue(item, out count))
counts[item] = ++count;
else
counts.Add(item, count = 1);
if (count <= times)
yield return item;
}
}
....
int[] source = new int[] { 1, 2, 3, 4, 1, 1, 2, 3 };
int[] result = RepeatOnly(source, 2).ToArray();
Console.Write(string.Join(Environment.NewLine, result));
I'd use a dictionary to keep track of how many times each integer has been encountered:
int[] intArray = { 1, 2, 3, 4, 1, 1, 2, 3 };
int N = 2;
var lookup = new Dictionary<int, int>();
LIst<int> list = new List<int>();
foreach (int num in intArray)
{
if (!lookup.ContainsKey(num))
{
lookup[num] = 1;
list.Add(num);
}
else if (lookup[num]++ < N)
{
list.Add(num);
}
}
I have been given this task to solve:
Write a program that reads an array of integers and removes from it a minimal number of elements in such a way that the remaining array is sorted in increasing order. Print the minimal number of elements that need to be removed in order for the array to become sorted.
Time limit 0.1sec.
Sample test:
Input:
1,
4,
3,
3,
6,
3,
2,
3
Output:
3
Unfortunately, my program is slower. This is my code:
using System;
static bool CheckAscending(List<int> list)
{
bool ascending = true;
for (int i = 0; i < list.Count - 1; i++)
{
if (list[i] > list[i + 1])
{
ascending = false;
}
}
return ascending;
}
static void Main()
{
int n;
n = int.Parse(Console.ReadLine());
List<int> arr = new List<int>();
List<int> sorted = new List<int>();
int maxSubsetLenght = 0;
for (int i = 0; i < n; i++)
{
arr.Add(int.Parse(Console.ReadLine()));
}
for (int i = 1; i <= (int)Math.Pow(2, n) - 1; i++)
{
int tempSubsetLenght = 0;
List<int> temp = new List<int>();
for (int j = 1; j <= n; j++)
{
if (((i >> (j - 1)) & 1) == 1)
{
temp.Add(arr[j - 1]);
tempSubsetLenght++;
}
}
if ((tempSubsetLenght > maxSubsetLenght) && (CheckAscending(temp)))
{
sorted = temp;
maxSubsetLenght = tempSubsetLenght;
}
}
Console.WriteLine(n - sorted.Count);
}
Can someone help me to make my program a bit faster. I will be glad if you could answer in the near future.
Ok I found how to soleve it and thanks #Gabor for your help :). Here is my solution:
using System;
static void Main(string[] args)
{
int n = int.Parse(Console.ReadLine());
List<int> numbers = new List<int>();
for (int i = 0; i < n; i++)
{
int currentNumber = int.Parse(Console.ReadLine());
numbers.Add(currentNumber);
}
int[] size = new int[numbers.Count];
// Define each number as subsequence.
for (int i = 0; i < numbers.Count; i++)
{
size[i] = 1;
}
int max = 1;
// Compare current number with the numbers before.
for (int i = 1; i < numbers.Count; i++)
{
for (int j = 0; j < i; j++)
{
if (numbers[i] >= numbers[j] && size[i] <= size[j] + 1)
{
size[i] = size[j] + 1;
// Update max increasing subsequence.
if (max < size[i])
{
max = size[i];
}
}
}
}
// Print numbers to remove as a result.
int numbersToRemove = n - max;
Console.WriteLine(numbersToRemove);
}
I think it would be helpful for other people, who have the same task to do like me.
UPDATE #2
When there is a decrease then we should delete not only the current number but all the numbers before which are more than the new minValue.
The Stopwatch is in the System.Diagnostic namespace.
// int?[] numbers = new int?[] { 8, 1, 4, 3, 3, 6, 3, 2, 3 };
int?[] numbers = new int?[] { -7, -7, -7, -100, -100, -99, 4, -90, -80, -70 };
Console.WriteLine("Array: [{0}]", String.Join(", ", numbers));
System.Diagnostics.Stopwatch watch = new Stopwatch();
watch.Start();
int minValue = Int32.MinValue;
for (int i = 0; i < numbers.Length - 1; i++)
{
var currentNumber = numbers[i];
var nextNumber = numbers[i + 1];
if (currentNumber > nextNumber)
{
if (nextNumber < minValue)
{
numbers[i + 1] = null;
}
else
{
minValue = nextNumber.Value;
for (int j = i; j >= 0; j--)
{
if (numbers[j] > minValue)
{
numbers[j] = null;
}
}
}
}
}
watch.Stop();
Console.WriteLine("Result: {0}; Time: {1} ms", numbers.Count(number => number == null), watch.ElapsedMilliseconds);
Console.WriteLine("Array: [{0}]", String.Join(", ", numbers));
I couldn't get it to work, I am trying to arrange the values of the array in ascending order by using for loop.
int[] arr = new int[5] { 5, 6, 2, 4, 1 };
for (int i = 0; i <= arr.Length; i++)
{
if (arr[i] > arr[i + 1])
{
int temp = arr[i + 1];
arr[i] = arr[i + 1];
arr[i] = temp;
}
Console.Write(arr[i]);
}
I am assuming that you are not using Array.Sort because you are doing this as a learning exercise; there is no other way to avoid this very common library function.
The reason your algorithm does not work is that it is not enough to go through an array once, and swap items that are out of order. Try doing this as a mental experiment, when the array is almost sorted, but the first element is at the end, like this:
2 3 4 5 6 7 1
A single path would bring you closer, but it wouldn't bring you all the way to a sorted array:
2 3 4 5 6 1 7
As you can see, you have to repeat this process multiple times, until the array is sorted. How do you know that the array is sorted? You know that when the entire inner loop did not have a single swap.
Here is how you can implement this:
bool didSwap;
do {
didSwap = false;
for (int i = 0; i < arr.Length-1; i++)
{
if (arr[i] > arr[i + 1])
{
int temp = arr[i + 1];
arr[i + 1] = arr[i];
arr[i] = temp;
didSwap = true;
}
}
} while (didSwap);
for (int i = 0; i != arr.Length ; i++) {
Console.Write(arr[i]);
}
Note several changes from your code:
The printing is done in the separate loop, after the sorting is complete
The loop goes to arr.length-1, not to arr.length, because otherwise your last check will go outside the bounds of the array.
This sorting algorithm is called Bubble Sort. There are various optimizations to this algorithm that can make it go slightly faster.
In general, bubble sort is among the slower sorting algorithms. When the number of items to sort is high, you should consider an advanced algorithm, or use the library implementation.
int[] Array = { 11, 33, 5, -3, 19, 8, 49 };
int temp;
for (int i = 0; i < Array.Length - 1; i++)
{
for (int j = i + 1; j < Array.Length; j++)
{
if (Array[i] > Array[j])
{
temp = Array[i];
Array[i] = Array[j];
Array[j] = temp;
}
}
}
Console.Write("Sorted:");
foreach (int sort in Array)
Console.Write("{0} ", sort);
If you want to make your own sorting, then it's not enough to just loop through the items once and swap them. The closest to that is the bubble sort algorithm, where you loop over the array repeatedly until there is no more items to swap:
int[] arr = new int[5] { 5, 6, 2, 4, 1 };
bool swapped = true;
while (swapped) {
swapped = false;
for (int i = 0; i < arr.Length - 1; i++) {
if (arr[i] > arr[i + 1]) {
swapped = true;
int temp = arr[i + 1];
arr[i] = arr[i + 1];
arr[i] = temp;
}
}
}
for (int i = 0; i < arr.Length - 1; i++) {
Console.Write(arr[i]);
}
There are also built in methods to sort data, which is easier to use, more efficient, and already thoroughly tested:
int[] arr = new int[5] { 5, 6, 2, 4, 1 };
Array.Sort(arr);
Use Linq Order by:
int[] arr = new int[5] { 5, 6, 2, 4, 1 };
int[] ascOrderedArray = (from i in arr orderby i ascending select i).ToArray();
I think it could be easy and why do you need for loop.
using System;
namespace bubble_sort
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
int[] arr = new int[50];
int n;
Console.WriteLine("Enter no of elements you want to store in an array");
n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter elements in an array");
for (int i = 1; i <= n; i++)
{
arr[i] = Convert.ToInt32(Console.ReadLine());
}
p.bubblesort(arr, n);
Console.ReadKey();
}
public void bubblesort(int[] arr, int n)
{
int temp;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n - i; j++)
{
if (arr[j] > arr[j + 1])
{
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
Console.WriteLine("Array after sorting");
for (int i = 1; i <= n; i++)
{
Console.WriteLine(arr[i]);
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace basicsorting
{
public class Program
{
public static void Main(string[] args)
{
int i2, k, j;
Console.WriteLine("How many elements you want to sort? ");
i2 = Convert.ToInt32(Console.ReadLine());
int[] values = new int[i2];
int n1 = 0;
int n = 0; ;
int i;
Console.WriteLine("Enter the elements of array {0}", n1);
for (i = 0; i < i2; i++)
{
Console.WriteLine("Enter the elements of array {0}");
n = Convert.ToInt32(Console.ReadLine());
Convert.ToInt32(values[i] = n);
}
for (i = 0; i < i2; i++)
{
k = Convert.ToInt32(values[i]);
for (j = i - 1; j >= 0 && k < values[j]; j--)
values[j + 1] = values[j];
values[j + 1] = k;
}
for (i = 0; i < i2; i++)
{
Console.WriteLine("sorting elements {0}", values[i]);
}
Console.ReadLine();
}
}
}
int[] array = new int[] { 8, 9, 5, 6, 7, 4, 3, 2, 1 };
int[] outPut = new int[] { };
int temp = 0;
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
var first = array[i];
var second = array[j];
if (array[i] < array[j]) {
temp = first;
array[i] = second;
array[j] = temp;
}
}
}
foreach (var item in array) {
Console.WriteLine(item);
}
Console.ReadKey();
}
foreach (var item in array) {
Console.WriteLine(item);
}
Console.ReadKey();
int temp = 0;
int[] arr = new int[] { 5, 6, 2, 4, 1 };
for (int i = 0; i <= arr.Length - 1; i++)
{
for (int j = i + 1; j <= arr.Length - 1; j++)
{
if (arr[i] > arr[j]) //> Asecnding Order < Desending Order
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
Console.Write(arr[i]);
}
Console.ReadLine();
public int[] sortArray(params int[] numbers)
{
for(int i = 0; i < numbers.Length; i++)
{
for(int j = i + 1; j < numbers.Length; j++)
{
if (numbers[i] < numbers[j])
{
continue;
}else if (numbers[i] > numbers[j])
{
int temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}
}
}
return numbers;
}
You should do like :
int[] arr = new int[5] { 5, 6, 2, 4, 1 };
for (int i = 0; i < arr.Length-1; i++)
{
if (arr[i] < arr[i + 1])
{
int temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
}
// to verify sorted Array
for (int i = 0; i < arr.Length; i++)
{
console.write( arr[i].ToString());
}
For last 1 you need not to check it will be automatically ordered.
#Jon Skeet They wanted to use a for loop.
There are numerous types of sorts. The simplest is Bubble Sort.
int[] arr = new int[5] { 5, 6, 2, 4, 1 };
//bubble sort
for (int i = arr.Length - 1; i > 0; i--)
{
for (int j = 0; j <= i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
int highValue = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = highValue;
}
}
}
foreach(int i in arr) Console.Write(i);