Rechange array so it could be sorted in C# - c#

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));

Related

Digit difference sort

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 + " ");
}
}
}

How to find the maximal (longest) sequence of increasing elements in an array arr[n]?

I need to write a program, which finds the maximal sequence of increasing elements in an array arr[n]. It is not necessary the elements to be consecutively placed. E.g.: {9, 6, 2, 7, 4, 7, 6, 5, 8, 4} -> {2, 4, 6, 8}.
I have some guidelines to use 2 nested loops and one additional array.
So far i know how to use if statements, loops and little arrays.
Any suggestions pls...?
This is my start so far (am I on a good track?):
Console.Write("Elements in array: ");
int n = int.Parse(Console.ReadLine());
int[] arr = new int[n];
int[] result;
for (int index = 0; index < arr.Length; index++)
{
Console.Write("Array [{0}] = ", index);
arr[index] = int.Parse(Console.ReadLine());
}
for (int indexOut = 0; indexOut < n; indexOut++)
{
for (int indexIn = 1; indexIn < n; indexIn++)
{
}
}
nested loops are 1 loop inside another:
for (int 1 = 0; i < something.length; i++) {
for ( int j = 0; j < somethingElse.length; j++) {
// code
}
}
I think I found your solution here:
http://www.geeksforgeeks.org/dynamic-programming-set-3-longest-increasing-subsequence/
/* Dynamic Programming C/C++ implementation of LIS problem */
#include<stdio.h>
#include<stdlib.h>
/* lis() returns the length of the longest increasing
subsequence in arr[] of size n */
int lis( int arr[], int n )
{
int *lis, i, j, max = 0;
lis = (int*) malloc ( sizeof( int ) * n );
/* Initialize LIS values for all indexes */
for ( i = 0; i < n; i++ )
lis[i] = 1;
/* Compute optimized LIS values in bottom up manner */
for ( i = 1; i < n; i++ )
for ( j = 0; j < i; j++ )
if ( arr[i] > arr[j] && lis[i] < lis[j] + 1)
lis[i] = lis[j] + 1;
/* Pick maximum of all LIS values */
for ( i = 0; i < n; i++ )
if ( max < lis[i] )
max = lis[i];
/* Free memory to avoid memory leak */
free( lis );
return max;
}
/* Driver program to test above function */
int main()
{
int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 };
int n = sizeof(arr)/sizeof(arr[0]);
printf("Length of LIS is %d\n", lis( arr, n ) );
return 0;
}
You will have to modify it a little to generate the actual array.
My code:
// Arr[]
int n = 10;
int[] arr = new int[n];
for (int index = 0; index < n; index++)
{
Console.Write("Array[{0}] = ", index);
arr[index] = int.Parse(Console.ReadLine());
}
// Len[]
int[] len = new int[n];
for (int index = 0; index < n; index++)
{
len[index] = 1;
}
// Correct len[]
for (int indexCount = 1; indexCount < n; indexCount++)
{
for (int indexNumber = 0; indexNumber < indexCount; indexNumber++)
{
if (arr[indexCount] > arr[indexNumber] && len[indexCount] < len[indexNumber] + 1)
{
len[indexCount] = len[indexNumber] + 1;
}
}
}
// Print new len[]
// Just to keep track of numbers
Console.WriteLine();
Console.Write("{");
for (int index = 0; index < n; index++)
{
Console.Write(" " + len[index] + " ");
}
Console.WriteLine("}");
// Search for the max number in len[]
int max = int.MinValue;
int maxPosition = 0;
for (int index = 0; index < len.Length; index++)
{
if (len[index] > max)
{
max = len[index];
maxPosition = index;
}
}
// Create the result in result[]
int[] result = new int[max];
int i = (max - 1);
int maxCount = max;
for (int index = maxPosition; index >= 0; index--)
{
if (len[index] == max)
{
result[i] = arr[index];
max--;
i--;
}
}
// Print the result[]
Console.WriteLine();
Console.Write("{");
for (int index = 0; index < maxCount; index++)
{
Console.Write(" " + result[index] + " ");
}
Console.WriteLine("}");
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int maincount = 0;
int indices = 0;
int increment = 0;
int count = 0;
int finalcount = 0;
int checkvalue = 0;
string consincval = null;
string consincval1 = null;
string finalconsincval = null;
Console.WriteLine("Enter number of rows of the array");
int len = int.Parse(Console.ReadLine());
Console.WriteLine("Enter number of columns of the array");
int wid = int.Parse(Console.ReadLine());
int[,] consecincrease = new int[len, wid];
Console.WriteLine("Enter the Values of array");
for (int index = 0; index < consecincrease.GetLength(0); index++)
{
for (int index1 = 0; index1 < consecincrease.GetLength(1); index1++)
{
consecincrease[index, index1] = int.Parse(Console.ReadLine());
Console.Write("The value of the {0} {1}" + ":" + " " + "{2}", index, index1, consecincrease[index, index1]);
Console.WriteLine();
}
}
for (int index = 0; index < consecincrease.GetLength(0); index++)
{
for (int index1 = 0; index1 < consecincrease.GetLength(1); index1++)
{
increment = 0;
checkvalue = consecincrease[index, index1];
for ( indices = increment; indices < consecincrease.GetLength(1)-1; indices++)
{
if (checkvalue < consecincrease[index, indices +1])
{
consincval = Convert.ToString(checkvalue);
count++;
maincount = count;
checkvalue = consecincrease[index, indices+1];
consincval1 = consincval1 + " " + consincval + " ";
}
}
if (count == 0)
{
}
else if (count >= 1)
{
consincval = Convert.ToString(checkvalue);
count++;
maincount = count;
consincval1 = consincval1 + " " + consincval + " ";
}
if (finalcount < maincount)
{
finalcount = maincount;
finalconsincval = consincval1;
count = 0;
consincval1 = null;
consincval = null;
}
else
{
count = 0;
consincval1 = null;
consincval = null;
}
increment ++;
}
}
Console.WriteLine();
Console.WriteLine(finalconsincval);
Console.ReadLine();
}
}
}

Arranging values of array in Ascending order

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);

Simple bubble sort c#

int[] arr = {800,11,50,771,649,770,240, 9};
int temp = 0;
for (int write = 0; write < arr.Length; write++)
{
for (int sort = 0; sort < arr.Length - 1; sort++)
{
if (arr[sort] > arr[sort + 1])
{
temp = arr[sort + 1];
arr[sort + 1] = arr[sort];
arr[sort] = temp;
}
}
Console.Write("{0} ", arr[write]);
}
All I am attempting to do is a simple bubble sort with this array. I would like to figure out why the sorting is screwed up.
In example, here is when the array is {800,11,50,771,649,770,240, 9}:
Here is what gets displayed: 11, 50, 649, 9, 649, 770, 771, 800
I am thinking that I might be missing something in the comparison.
No, your algorithm works but your Write operation is misplaced within the outer loop.
int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };
int temp = 0;
for (int write = 0; write < arr.Length; write++) {
for (int sort = 0; sort < arr.Length - 1; sort++) {
if (arr[sort] > arr[sort + 1]) {
temp = arr[sort + 1];
arr[sort + 1] = arr[sort];
arr[sort] = temp;
}
}
}
for (int i = 0; i < arr.Length; i++)
Console.Write(arr[i] + " ");
Console.ReadKey();
This one works for me
public static int[] SortArray(int[] array)
{
int length = array.Length;
int temp = array[0];
for (int i = 0; i < length; i++)
{
for (int j = i+1; j < length; j++)
{
if (array[i] > array[j])
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
return array;
}
public static void BubbleSort(int[] a)
{
for (int i = 1; i <= a.Length - 1; ++i)
for (int j = 0; j < a.Length - i; ++j)
if (a[j] > a[j + 1])
Swap(ref a[j], ref a[j + 1]);
}
public static void Swap(ref int x, ref int y)
{
int temp = x;
x = y;
y = temp;
}
int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };
int temp = 0;
for (int write = 0; write < arr.Length; write++)
{
for (int sort = 0; sort < arr.Length - 1 - write ; sort++)
{
if (arr[sort] > arr[sort + 1])
{
temp = arr[sort + 1];
arr[sort + 1] = arr[sort];
arr[sort] = temp;
}
}
}
for (int i = 0; i < arr.Length; i++) Console.Write(arr[i] + " ");
Console.ReadKey();
I saw someone use this example as part of a job application test. My feedback to him was that it lacks an escape from the outer loop when the array is mostly sorted.
consider what would happen in this case:
int[] arr = {1,2,3,4,5,6,7,8};
here's something that makes more sense:
int[] arr = {1,2,3,4,5,6,7,8};
int temp = 0;
int loopCount=0;
bool doBreak=true;
for (int write = 0; write < arr.Length; write++)
{
doBreak=true;
for (int sort = 0; sort < arr.Length - 1; sort++)
{
if (arr[sort] > arr[sort + 1])
{
temp = arr[sort + 1];
arr[sort + 1] = arr[sort];
arr[sort] = temp;
doBreak=false;
}
loopCount++;
}
if(doBreak){ break; /*early escape*/ }
}
Console.WriteLine(loopCount);
for (int i = 0; i < arr.Length; i++) Console.Write(arr[i] + " ");
public static int[] BubbleSort(int[] arr)
{
int length = arr.Length();
while (length > 0)
{
int newLength = 0;
for (int i = 1; i < length; i++)
{
if (arr[i - 1] > arr[i])
{
Swap(ref arr[i - 1], ref arr[i]);
newLength = i;
}
}
length = newLength;
}
}
public static void Swap(ref int x, ref int y)
{
int temp = y;
y = x;
x = temp;
}
I wanted to add to the accepted answer something different:
Number of iterations can be reduced as well, as below.
int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };
int temp = 0;
int arrLength = arr.Length;
for (int write = 0; write < arr.Length - 1; write++, arrLength--)
{
for (int sort = 0; sort < arrLength - 1; sort++)
{
if (arr[sort] > arr[sort + 1])
{
temp = arr[sort + 1];
arr[sort + 1] = arr[sort];
arr[sort] = temp;
}
}
}
foreach (var item in arr)
{
Console.WriteLine(item);
}
Your Console.Write("{0} ", arr[write]); is too early. You're printing the values while the sort is still in progress. For example, you're printing 9 as being index 3 in the array, yet on the very next iteration of the loop the 9 has moved to index 2 and 240 has moved to index 3... yet you're outer loop has moved forward so it prints 649 the second time and 240 never gets printed.
int[] array = new int[10] { 13, 2, 5, 8, 23, 90, 41, 4, 77, 61 };
for (int i = 10; i > 0; i--)
{
for (int j = 0; j < 9; j++)
{
if (array[j] > array[j + 1])
{
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
static bool BubbleSort(ref List<int> myList, int number)
{
if (number == 1)
return true;
for (int i = 0; i < number; i++)
{
if ((i + 1 < number) && (myList[i] > myList[i + 1]))
{
int temp = myList[i];
myList[i] = myList[i + 1];
myList[i + 1] = temp;
}
else
continue;
}
return BubbleSort(ref myList, number - 1);
}
Just another example but with an outter WHILE loop instead of a FOR:
public static void Bubble()
{
int[] data = { 5, 4, 3, 2, 1 };
bool newLoopNeeded = false;
int temp;
int loop = 0;
while (!newLoopNeeded)
{
newLoopNeeded = true;
for (int i = 0; i < data.Length - 1; i++)
{
if (data[i + 1] < data[i])
{
temp = data[i];
data[i] = data[i + 1];
data[i + 1] = temp;
newLoopNeeded = false;
}
loop++;
}
}
}
Bubble sort with sort direction -
using System;
public class Program
{
public static void Main(string[] args)
{
var input = new[] { 800, 11, 50, 771, 649, 770, 240, 9 };
BubbleSort(input);
Array.ForEach(input, Console.WriteLine);
Console.ReadKey();
}
public enum Direction
{
Ascending = 0,
Descending
}
public static void BubbleSort(int[] input, Direction direction = Direction.Ascending)
{
bool swapped;
var length = input.Length;
do
{
swapped = false;
for (var index = 0; index < length - 1; index++)
{
var needSwap = direction == Direction.Ascending ? input[index] > input[index + 1] : input[index] < input[index + 1];
if (needSwap)
{
var temp = input[index];
input[index] = input[index + 1];
input[index + 1] = temp;
swapped = true;
}
}
} while (swapped);
}
}
This is what I wrote using recursive methods:
public static int[] BubbleSort(int[] input)
{
bool isSorted = true;
for (int i = 0; i < input.Length; i++)
{
if (i != input.Length - 1 && input[i] > input[i + 1])
{
isSorted = false;
int temp = input[i];
input[i] = input[i + 1];
input[i + 1] = temp;
}
}
return isSorted ? input : BubbleSort(input);
}
It does the same in a more elegant way.
var arrayValues = new[] { 99, 12, 11, 300, 400, 10, 9, 3, 6, 5, 7, 8};
for (var mainLoop = 0; mainLoop < arrayValues.Length; mainLoop++)
{
for (var innerLoop = mainLoop + 1; innerLoop < arrayValues.Length; innerLoop++)
{
if (arrayValues[mainLoop] <= arrayValues[innerLoop])
{
continue;
}
var temp = arrayValues[mainLoop];
arrayValues[mainLoop] = arrayValues[innerLoop];
arrayValues[innerLoop] = temp;
}
}
So i did mine as a recursive function (no need for the nested loop), perhaps someone could comment if this is inefficient (when compared to the other solutions).
public static int[] BubbleSort(int[] arrayOfValues)
{
var swapOccurred = false;
for (var i = 0; i < arrayOfValues.Length; i++)
{
if (i == arrayOfValues.Length - 1)
continue;
if (arrayOfValues[i] > arrayOfValues[i + 1])
{
//swap values
var current = arrayOfValues[i];
var next = arrayOfValues[i + 1];
arrayOfValues[i] = next;
arrayOfValues[i + 1] = current;
swapOccurred = true;
}
}
if (swapOccurred)
{
// keep going until no further swaps are required:
BubbleSort(arrayOfValues);
}
return arrayOfValues;
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Practice {
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the size");
int n = Convert.ToInt32(Console.ReadLine());
int[] mynum = new int[n];
Console.WriteLine("Enter the Numbers");
for (int p = 0; p < n;p++ )
{
mynum[p] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("The number are");
foreach(int p in mynum)
{
Console.WriteLine(p);
}
for (int i = 0; i < n;i++ )
{
for(int j=i+1;j<n;j++)
{
if(mynum[i]>mynum[j])
{
int x = mynum[j];
mynum[j] = mynum[i];
mynum[i] = x;
}
}
}
Console.WriteLine("Sortrd data is-");
foreach(int p in mynum)
{
Console.WriteLine(p);
}
Console.ReadLine();
}
} }
int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };
for (int i = 0; i < arr.Length; i++)
{
for (int j = i; j < arr.Length ; j++)
{
if (arr[j] < arr[i])
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
Console.ReadLine();
public void BubbleSortNum()
{
int[] a = {10,5,30,25,40,20};
int length = a.Length;
int temp = 0;
for (int i = 0; i <length; i++)
{
for(int j=i;j<length; j++)
{
if (a[i]>a[j])
{
temp = a[j];
a[j] = a[i];
a[i] = temp;
}
}
Console.WriteLine(a[i]);
}
}

Longest subsequence in array

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();
}

Categories

Resources