Advertisement
ivandrofly

Rotate a Array

Mar 5th, 2015
411
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.22 KB | None | 0 0
  1. using System;
  2.  
  3. namespace ConsoleApplication2
  4. {
  5.     class Program
  6.     {
  7.         //Function to reverse arr[] from index start to end
  8.         static void reverseArray(int[] arr, int start, int end)
  9.         {
  10.             int i;
  11.             int temp;
  12.             while (start < end)
  13.             {
  14.                 temp = arr[start];
  15.                 arr[start] = arr[end];
  16.                 arr[end] = temp;
  17.                 start++;
  18.                 end--;
  19.             }
  20.         }
  21.  
  22.         //Function to left rotate arr[] of size n by d
  23.         static void leftRotate(int[] arr, int d, int n)
  24.         {
  25.             reverseArray(arr, 0, d - 1);
  26.             reverseArray(arr, d, n - 1);
  27.             reverseArray(arr, 0, n - 1);
  28.         }
  29.  
  30.         // Function to print an array
  31.         static void printArray(int[] arr, int size)
  32.         {
  33.             int i;
  34.             for (i = 0; i < size; i++)
  35.                 Console.WriteLine(arr[i]);
  36.         }
  37.  
  38.         //Driver program to test above functions
  39.         static void Main(string[] args)
  40.         {
  41.             int[] arr = new[] { 4, 8, 15, 16, 23, 42, 99 };
  42.  
  43.             leftRotate(arr, 3, 7);
  44.             printArray(arr, 7);
  45.         }
  46.     }
  47. }
  48.  
  49. // Found on Internet
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement