DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

# Snippets

## Recent Snippets

### Sort Linked List In Ascending Order - C#

06/04/12 by Aniruddha Deshpande in C#
```                    /// <summary>
/// This method sorts elements in linked list and returns a new sorted linked list
/// </summary>
/// <param name="count">number of elements in unsorted linked list</param>
{
// Basic Algorithm Steps
//1. Find Min Node
//2. Remove Min Node and attach it to new Sorted linked list
//3. Repeat "count" number of times

Node _previous = _current;

Node _min = _current;
Node _minPrevious = _min;

for (int i = 0; i < count; i++)
{
_min = _current;
_minPrevious = _min;

//Find min Node
while (_current != null)
{
if (_current.Data < _min.Data)
{
_min = _current;
_minPrevious = _previous;
}
_previous = _current;
_current = _current.Next;
}

// Remove min Node
{
}
else if (_min.Next == null) //if tail is min node
{
_minPrevious.Next = null;
}
else
{
_minPrevious.Next = _minPrevious.Next.Next;
}

//Attach min Node to the new sorted linked list
{
_sortedListTail.Next = _min;
_sortedListTail = _sortedListTail.Next;
}
else
{
}
}

}                ```

### Selection Sort - C#

06/04/12 by Aniruddha Deshpande in C#
```                    public int[] SelectionSort(int[] arr)
{
//1. Find min
//2. Swap it with first element
//3. Repeat starting from secong position onwards.
int _min = 0;
for (int i = 0; i < arr.Length; i++)
{
_min = i;
for (int j = i; j < arr.Length; j++)
{
if (arr[j] < arr[_min])
_min = j;
}
int _temp = arr[i];
arr[i] = arr[_min];
arr[_min] = _temp;
}
return arr;
}                ```

### Bubble Sort - C#

06/04/12 by Aniruddha Deshpande in C#
```                    public int[] BubbleSort(int[] _arr)
{
for (int i = _arr.Length - 1; i > 0; i--)
{
for (int j = 0; j < i; j++)
{
if (_arr[j] > _arr[j + 1])
{
int temp = _arr[j];
_arr[j] = _arr[j + 1];
_arr[j + 1] = temp;
}
}
}
return _arr;
}                ```

### Find All Permutations Of String - C#

06/02/12 by Aniruddha Deshpande in C#
```                    // 1. remove first char
// 2. find permutations of the rest of chars
// 3. Attach the first char to each of those permutations.
//     3.1  for each permutation, move firstChar in all indexes to produce even more permutations.
// 4. Return list of possible permutations.

public string[] FindPermutations(string word)
{
if (word.Length == 2)
{
char[] _c = word.ToCharArray();
string s = new string(new char[] { _c[1], _c[0] });
return new string[]
{
word,
s
};
}

List<string> _result = new List<string>();

string[] _subsetPermutations = FindPermutations(word.Substring(1));
char _firstChar = word[0];
foreach (string s in _subsetPermutations)
{
string _temp = _firstChar.ToString() + s;
char[] _chars = _temp.ToCharArray();
for (int i = 0; i < _temp.Length - 1; i++)
{
char t = _chars[i];
_chars[i] = _chars[i + 1];
_chars[i + 1] = t;
string s2 = new string(_chars);
}
}
return _result.ToArray();
}                ```

### Find If Number Is Prime - C#

06/02/12 by Aniruddha Deshpande in C#
```                    public bool IsPrime(int num)
{
bool _isPrime = true;

if (num % 2 == 0) return false;

for (int i = 3; i <= Convert.ToInt32(Math.Sqrt(num)); i = i + 2)
{
if (num % i == 0)
{
_isPrime = false;
break;
}
}
return _isPrime;
}                ```

### Finding Nth Fibonacci Number In Recursive Way - C#

06/02/12 by Aniruddha Deshpande in C#
```                    public int FindNthFibonacciNumber(int n)
{
if (n == 1 || n == 2) return 1;

int nthfibonacciNumber = FindNthFibonacciNumber(n - 1) + FindNthFibonacciNumber(n - 2);
return nthfibonacciNumber;
}                ```

### Depth First Search - C#

06/01/12 by Aniruddha Deshpande in C#
```                            public class BinaryTreeNode
{
public BinaryTreeNode Left { get; set; }

public BinaryTreeNode Right { get; set; }

public int Data { get; set; }
}

public class DepthFirstSearch
{
private Stack<BinaryTreeNode> _searchStack;
private BinaryTreeNode _root;

public DepthFirstSearch(BinaryTreeNode rootNode)
{
_root = rootNode;
_searchStack = new Stack<BinaryTreeNode>();
}

public bool Search(int data)
{
BinaryTreeNode _current;
_searchStack.Push(_root);
while (_searchStack.Count != 0)
{
_current = _searchStack.Pop();
if (_current.Data == data)
{
return true;
}
else
{
_searchStack.Push(_current.Right);
_searchStack.Push(_current.Left);
}
}
return false;
}
}                ```

### Breadth First Search - C#

06/01/12 by Aniruddha Deshpande in C#
```                    class BinaryTreeNode
{
public BinaryTreeNode Left { get; set; }

public BinaryTreeNode Right { get; set; }

public int Data { get; set; }
}

{
private Queue<BinaryTreeNode> _searchQueue;
private BinaryTreeNode _root;

{
_searchQueue = new Queue<BinaryTreeNode>();
_root = rootNode;
}

public bool Search(int data)
{
BinaryTreeNode _current = _root;
_searchQueue.Enqueue(_root);

while (_searchQueue.Count != 0)
{
_current = _searchQueue.Dequeue();
if (__current.Data == data)
{
return true;
}
else
{
_searchQueue.Enqueue(_current.Left);
_searchQueue.Enqueue(_current.Right);
}
}

return false;
}
}                ```

### Implement 3 Stacks Using Single Array - C#

06/01/12 by Aniruddha Deshpande in C#
```                    /// <summary>
/// 3 Stacks are Implemented in this class using 1 array
/// </summary>
public class StacksUsingSingleArray
{
private static int _arrSize = 99;
private int[] _arr = new int[_arrSize];
private int[] _stacksAvailableSlots = new int[3];
private int _stackSize = 0;

public StacksUsingSingleArray()
{
_stackSize = _arrSize / 3;
_stacksAvailableSlots[0] = 0 * _stackSize;
_stacksAvailableSlots[1] = 1 * _stackSize; //33
_stacksAvailableSlots[2] = 2 * _stackSize; //66

}

/// <summary>
/// Push item on stack
/// </summary>
/// <param name="stackNum">stack number (ie. 0/1/2)</param>
/// <param name="data"></param>
public void PushOnStack(int stackNum, int data)
{
_arr[_stacksAvailableSlots[stackNum]++] = data;
}

/// <summary>
/// Pop item from stack
/// </summary>
/// <param name="stackNum">stack number (ie. 0/1/2)</param>
public int PopStack(int stackNum)
{
return _arr[--_stacksAvailableSlots[stackNum]];
}

/// <summary>
/// Gives count of items in a stack
/// </summary>
/// <param name="stackNum">stack number (ie. 0/1/2)</param>
/// <returns></returns>
public int StackCount(int stackNum)
{
return (_stacksAvailableSlots[stackNum] - (_stackSize * stackNum));
}

/// <summary>
/// Printing contents of stack
/// </summary>
/// <param name="stackNum">stack number (ie. 0/1/2)</param>
public void PrintStack(int stackNum)
{
for (int i = stackNum * _stackSize; i < _stacksAvailableSlots[stackNum]; i++)
{
Console.WriteLine(_arr[i]);
}
}
}                ```

### Queue Using 2 Stacks - C#

05/25/12 by Aniruddha Deshpande in C#
```                    public class QueueUsing2Stacks
{
private Stack _stack1 = new Stack();
private Stack _stack2 = new Stack();

public QueueUsing2Stacks() { }

public void Enqueue(int data)
{
//Pop ALL existing elements from stack1, push them onto stack2
int _stack1Count = _stack1.Count;
for (int i = 0; i < _stack1Count; i++)
{
_stack2.Push(_stack1.Pop());
}
//Push new data onto stack1
_stack1.Push(data);

int _stack2Count = _stack2.Count;
//Pop ALL elements from stack2 and Push them back onto stack1
for (int i = 0; i < _stack2Count; i++)
{
_stack1.Push(_stack2.Pop());
}
}

public int Dequeue()
{
if (_stack1.Count == 0)
throw new Exception("Queue is Empty");

return _stack1.Pop();
}
}                ```
"Starting from scratch" is seductive but disease ridden