Replacing two consecutive cell in an array with one cell - c#

I was just asking if there is a simple way of doing this.
i.e. Replacing two consecutive cell with one cell having different value.
For ex: - if my array =[0,3,1,2,3,4], and i want to replace index 0,and 1 with the value 5
to become like this array=[5,1,2,3,4]
Can you guys suggest some simple way for doing this.
i do this code but there is something wrong:
int J = 0;
if (max != 1)
{
for (int iii = 0; iii < output.Length -1; iii++)
{
if ((output[iii] == imax) && (output[iii + 1] == jmax))
{
temp = temp + 1;
output[J] = Convert.ToByte(temp);
J = J + 1;
iii = iii + 1;
}
else
{
output[J] = output[iii];
J = J + 1;
output[J] = output[iii + 1];
}
}
}
because when i want to check the 2 consecutive index ,i want to pass them to the anther 2 index

If you care about performance you want to do as little operations that can harm performance. Try this extension method:
public static int[] ReplaceConsecutiveCells(this int[] array, int startIndex, int replaceWith)
{
int[] targetArray = new int[array.Length - 1];
for (int i = 0; i < array.Length; i++)
{
if (i < startIndex)
{
targetArray[i] = array[i];
}
else if (i == startIndex)
{
targetArray[i] = replaceWith;
}
else if (i == startIndex + 1)
{
// no action
}
else
{
targetArray[i - 1] = array[i];
}
}
return targetArray;
}
Use it like this:
array = array.ReplaceConsecutiveCells(0, 5);

int[] array = new int[] { 0, 3, 1, 2, 3, 4 };
List<int> list = array.ToList();
list.RemoveRange(0,2);
list.Insert(0, 5);
array = list.ToArray();

Yet another variant
int[] array = new int[] { 0, 3, 1, 2, 3, 4 };
Array.Reverse(array);
Array.Resize(ref array, 5);
Array.Reverse(array);
array[0] = 5;

do
{
RNG_NXT =RNG +1;
for (int iii = 0; iii <Nold -1; iii++)
{
if ((output[iii] == imax) && (output[iii + 1] == jmax))
{
output[J] = Convert.ToByte(RNG_NXT);
J = J + 1;
iii = iii + 1;
}
else
{
output[J] = output[iii];
J = J + 1;
}
}
RNG++;
}
while( RNG < RNG_MAX) ;

Related

A multidimensional array with systematic selected elements in C#

The wished output is a lot of array that looks like this:
public decimal [] array 1 = {1, 1, 0, 0, 0};
public decimal [] array 2 = {0, 1, 1, 0, 0};
public decimal [] array 3 = {0, 0, 1, 1, 0};
public decimal [] array 4 = {0, 0, 0, 1, 1};
The dimension does not fit my problem, because the problem demands a array of 14 elements, but the idear is the same. The question is how do I create this in a smart way. I tried a "for loop" creating array 1, but as the loop carried on it overwrote array 1 with array 2:
class Program
{
public decimal[] array_1 = { 0, 0, 0, 0, 0 };
public void Main(string[] args)
{
for (int i = 0; i < 5; i++)
{
if (i == 0)
{
array_1 [i] = 1;
array_1 [i + 1] = 1;
}
else if (i == 1)
{
array_1[i] = 1;
array_1[i + 1] = 1;
}
else if (i == 2)
{
array_1[i] = 1;
array_1[i + 1] = 1;
}
else if (i == 3)
{
array_1[i] = 1;
array_1[i + 1] = 1;
}
else if (i == 4)
{
array_1[i] = 1;
array_1[i + 1] = 1;
}
}
}
}
The output of the above is a array with only ones and not four different arrays as firstly wished.
decimal[][] arrays = { array_1, array_2, array_3, array_4 };
for (int a = 0; a < arrays.Length; a++) {
for (int i = 0; i < arrays[a].Length; i++) {
arrays[a][i] = i == a || i == a+1 ? 1 : 0;
}
}
Or, you can create one two-dimensional array:
decimal[,] array = new decimal[4, 5];
for (int row = 0; row < array.GetLength(0); row++) {
for (int column = 0; column < array.GetLength(1); column++) {
array[row, column] = column == row || column == row+1 ? 1 : 0;
}
}
Use multidimensional array:
class Program
{
public decimal[,] arrayObj = new decimal[5, 5];
public void Main(string[] args)
{
for (int i = 0; i < 4; i++)
{
arrayObj[i][i] = 1;
arrayObj[i+1] = 1;
}
}
If you want a collection (say, decimal[][] - jagged array) of arrays, I suggest using Linq:
int n = 4;
decimal[][] arrays = Enumerable.Range(1, n)
.Select(index => Enumerable
.Range(1, n + 1)
.Select(x => (decimal) (x == index || x == index + 1 ? 1 : 0))
.ToArray())
.ToArray();
and then use the collection
decimal array1 = arrays[0];
Test
string report = string.Join(Environment.NewLine, arrays
.Select(array => string.Join(" ", array)));
Outcome:
1 1 0 0 0
0 1 1 0 0
0 0 1 1 0
0 0 0 1 1
If you insist on 2d array:
int n = 4;
decimal[,] arrays = new decimal[n, n + 1];
for (int i = 0; i < arrays.GetLength(0); ++i) {
arrays[i, i] = 1;
arrays[i, i + 1] = 1;
}

Array comma separated output values in c#

I want to sort this row:
5, 1, 6, 2, 4, 3
Here is my code:
int[] a = new int[] { 5, 1, 6, 2, 4, 3 };
int i, j, key;
for (i = 1; i < 6; i++)
{
key = a[i];
j = i - 1;
while (j >= 0 && key < a[j])
{
a[j + 1] = a[j];
j--;
}
a[j + 1] = key;
}
var result = string.Empty;
for (i = 0; i < 6; i++)
{
Console.WriteLine(string.Join(",",a[i]));
//Console.WriteLine(string.Concat(a[i], ","));
}
Console.ReadKey();
I want to print the comma separated output value like below
1,2,3,4,5,6
Can anyone help me out?
You were almost there in getting your output the way you want it.
The String.Join method takes as a second parameter an array, so you can directly pass it your a without the for loop:
Console.WriteLine(string.Join(",", a));
try,
int[] a = new int[] { 5, 1, 6, 2, 4, 3 };
int i, j, key;
var result = string.Empty;
for (i = 0; i < 6; i++)
{
for (j = i+1; j < 6; j++)
{
if (a[i] > a[j])
{
key = a[i];
a[i] = a[j];
a[j] = key;
}
}
result += a[i].ToString() + ((i == 5) ? "" : ",");
}
Console.WriteLine( result);
Console.ReadKey();
You also can try this way:
for (i = 0; i < 6; i++)
{
Console.Write(a[i].ToString());
if(i < 5)
Console.Write(",");
else
Console.WriteLine();
}

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

shifting array elements to right?

I can't use a built-in function for this, I must use my own logic.
I've done element shifting to the left side, but the right side doesn't work for me. Not sure why.
My method for left:
public int[] shiftLeft(int[] arr) {
int[] demo = new int[arr.length];
int index = 0;
for (int i = 0; i < arr.length - 1; i++) {
demo[index] = arr[i + 1];
index++;
}
return demo;
}
and my attempt for the right shifting:
public int[] shiftRight(int[] arr) {
int[] demo = new int[arr.length];
int index = 0;
for (int i = arr.length - 1; i >= 0; i--) {
demo[index] = arr[(i - 1 > 0) ? i - 1 : 0];
index++;
}
return demo;
}
What am I doing wrong?
By shifting I mean:
you have an array, 1 2 3 4 5 6
Shifting it to left by one: 2 3 4 5 6 1
Shifting it to right by one: 6 1 2 3 4 5
//right shift with modulus
for (int i = 0; i < arr.length; i++) {
demo[(i+1) % demo.length] = arr[i];
}
The easiest way to go:
public int[] shiftLeft(int[] arr)
{
int[] demo = new int[arr.Length];
for (int i = 0; i < arr.Length - 1; i++)
{
demo[i] = arr[i + 1];
}
demo[demo.Length - 1] = arr[0];
return demo;
}
public int[] shiftRight(int[] arr)
{
int[] demo = new int[arr.Length];
for (int i = 1; i < arr.Length; i++)
{
demo[i] = arr[i - 1];
}
demo[0] = arr[demo.Length - 1];
return demo;
}
LINQ solution, just to add some diversity.
static int[] LeftShift(int[] array)
{
// all elements except for the first one... and at the end, the first one. to array.
return array.Skip(1).Concat(array.Take(1)).ToArray();
}
static int[] RightShift(int[] array)
{
// the last element (because we're skipping all but one)... then all but the last one.
return array.Skip(array.Length - 1).Concat(array.Take(array.Length - 1)).ToArray();
}
Probably not recommended if performance matters (for large arrays).
I realize that the OP is not supposed to use a "built-in function".
public static int[] shiftRight(int[] arr){
int[] demo = new int[arr.Length];
for (int i = 0; i <= arr.Length - 2; i++)
{
demo[i + 1] = arr[i];
}
demo[0] = arr[arr.Length - 1];
return demo;
}
The problem here is that you need to special case the left shift of the first element. For every element but the first the new index of the value will be oldIndex - 1. This is essentially what the loop is doing. However the first element has a new index of oldLength - 1. This needs to be special cased somewhere in the code base.
Try this,
public int[] ShiftRight(int[] arr)
{
int[] demo = new int[arr.Length];
for (int i = 0; i < arr.Length; i++) {
demo[i] = arr[i == 0 ? (arr.Length - 1) : (i - 1)];
}
return demo;
}
Use Arra.Copy...
public int[] shiftLeft(int[] arr) {
var result = new int[arr.Length];
Array.Copy(arr, 1, result, 0, arr.Length - 1);
result[arr.Length - 1] = arr[0];
return result;
}
public int[] shiftRight(int[] arr) {
var result = new int[arr.Length];
Array.Copy(arr, 0, result, 1, arr.Length - 1);
result[0] = arr[arr.Length - 1];
return result;
}
Usually I use this code. You can rewrites to the array extension method.
public static T[] Shift<T>(T[] array, int shiftValue)
{
var newArray = new T[array.Length];
shiftValue -= array.Length;
if(shiftValue < 0)
{
shiftValue*=-1;
}
for(var i=0; i<array.Length; i++)
{
var index = (i + shiftValue) % array.Length;
newArray[i] = array[index];
}
return newArray;
}
maybe this works for anyone seeing this post :
private int[] shiftLinear(int[] linArray, int shift){
int length = linArray.Length;
int[] shifted = new int[length];
shift = shift % length;
if (shift >= 0) {
for (int n = shift ; n < length; n++) shifted[n] = linArray[n-shift];
if (shift != 0) for (int n = 0; n < shift; n++) shifted[n] = linArray[length-1-n];
} else {
for (int n = 0 ; n < length+shift; n++) shifted[n] = linArray[n-shift];
for (int n = length+shift; n < length ; n++) shifted[n] = linArray[n-length-shift];
}
return shifted;
}
Without using external array;
public static int[] right(int[] A)
{
var tempo = A[0];
for(var i=0; i<A.Length-1; i++)
{
var yolo = A[i + 1];
A[i + 1] = tempo;
tempo = yolo;
}
A[0] = tempo;
return A;
}
public static int[] left(int[] A)
{
var tempo = A[A.Length - 1];
for (var i = A.Length - 1; i >0; i--)
{
var yolo = A[i - 1];
A[i -1] = tempo;
tempo = yolo;
}
A[A.Length - 1] = tempo;
return A;
}
public int[] shiftRight(int[] arr)
{
int[] demo = new int[arr.length];
Array.Copy(arr,arr.Length-1,demo,0,1); // Copy last position to first
Array.Copy(arr,0,demo,1,arr.Length-1); // Copy the rest shifted one
return demo;
}

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

Categories

Resources