Question

Add reverse() method which reverses the content of array without using additional array. rotate(k) method which...

Add reverse() method which reverses the content of array without using additional array.
rotate(k) method which rotates left the content of array without using additional array
by k elements.


import java.util.*;
* Implementation of the ADT List using a fixed-length array.
*
* if insert is successful returns 1, otherwise 0;
* for successful insertion:
* list should not be full and p should be valid.
*
* if delete is successful returns 1, otherwise 0;
* for successful deletion:
* list should not be empty and p should be valid.
*/

   public class proj2 implements list{
       // class Variables
       protected int n, count;
       protected int arr[];   

       proj2(int k){ // List Constructor
           count = 0;
           n = k;
           //Allocate Space for array            
          arr = new int[n+1];// index 0 is not used
       }
        public boolean isEmpty(){return (count == 0);}
       public boolean isFull (){return (count == n);}
        public int   length (){return count;}

       // insert x at position p
       // for successful insertion:
       // list should not be full and p should be valid.
       //    valid p's are: p >= 1 and p <= count+1    
       public int insert(int x, int p){
           int i;
           System.out.printf("\n Insert %4d at position %2d.", x, p);
       if (isFull() || p < 1 || p > count + 1)
               return 0;
           // Shift from position p to right
           for (i = count ; i >= p ; i--)
               arr[i+1] = arr[i];
           // end for
           // insert x at position p          
           arr[p] = x;
           count++; // increment no. of elements.
           return 1; // successful insertion
       } // end insert

       // delete x at position p
       // for successful deletion:
       // list should not be empty and p should be valid.
       //    valid p's are: p >= 1 and p <= count    
       public int delete(int p){
           System.out.printf("\n Delete element at position %2d.", p);
           if ( isEmpty() || p < 1 || p > count)
               return 0;
           // Shift from position p + 1 to left
           for (int i = p ; i < count ; i++)
               arr[i] = arr[i+1];
           // end for
           count --; // decrement no. of elements
           return 1; // successful deletion
       }

       // sequential serach for x in the list
       // if successful return position of x in the list,
       // otherwise return 0;
       public int serachx(int x){
           System.out.printf("\n search for %4d", x);
           // complete the rest
           return 1;
       }
      
       // print list elements
       public void printlist(){
           int i;
           System.out.print("\n List contents: ");
       for (i = 1; i <= count; i++)
               System.out.printf("%4d, ", arr[i]);
           // enf for
        }       

       public static void main(String args[]) {
           int j, m, k, p, x, s;
           try{
           Scanner inf = new Scanner(System.in);  
           k = inf.nextInt(); // read list size
           // Create a List of type Integer of size n
           proj2 lst = new proj2(k);          

           // read m elements and insert in the list
           m = inf.nextInt(); // read no. of elements to insert
           System.out.printf("\nInsert %2d elements in the list", m);
           for(j = 1; j <= m; j++){
               x = inf.nextInt(); // read x
               p = inf.nextInt(); // read position
               s = lst.insert(x, p); // insert x at position p
               if (s == 1)
               System.out.printf("\nInserting %d at position %d was successful", x, p);              
               else
               System.out.printf("\nInserting %d at position %d was not successful", x, p);
           }// end for
           System.out.printf("\n\nList content after inserting %d elements", m);
           lst.printlist();
  
           // read m positions to delete from list
           m = inf.nextInt(); // read no. positions to delete
           System.out.printf("\n\nDelete %d elements from list", m);
           for(j = 1; j <= m; j++){
               p = inf.nextInt(); // read position
               s = lst.delete(p);
               if ( s == 1)
               System.out.printf("\nDeleting element at position %2d was successful", p);
               else
               System.out.printf("\nDeleting element at position %2d was not successful", p);
           }// end for
           System.out.printf("\n\nList content after deleting %d elements.", m);
           lst.printlist();
           inf.close(); // close input file
lst.reverse(); // reverse array elements
System.out.printf("\n\nList content after reversing.");
lst.printlist();
k = inf.nextInt(); // read k for rotate
lst.rotate(k); // rotate left by k elements
System.out.printf("\n\nList content after rotating %d.", k);
lst.printlist();
} catch (Exception e) {System.out.print("\nException " + e + "\n");}
       } // end main
   }// end class listarr

0 0
Add a comment Improve this question Transcribed image text
Answer #1

part 1:  Add reverse() method which reverses the content of array without using additional array.

If we want to reverse the elements of an array without using any extra space, then our approach is like swapping technique. Run a loop up to length(array) /2 and swap the first element with the last element, swap second elements with second last and so on until we reach the middle. ie. swap(a[i] , a[n - i - 1] );

part2. rotate(k) method which rotates left the content of array without using additional array by k elements.

Approach: If we want rotates left the contents of the array without using additional array by k elements then we will assign

a[i]= a[ ( i + k)%n ]

following is the neat and clean source code with comments

import java.util.*;

import java.io.*;

public class HomeworkLib {

// methode for reversing the array

static void reverse(int a[], int n)

{

for (int i = 0; i < n / 2; i++) // swapping the elements upto n/2 index

{

int k = a[i];

a[i] = a[n - i - 1];

a[n - i - 1] = k;

}

/*printing the reversed array*/

System.out.print("\nElements of array After the reversing : ");

for (int i = 0; i < n; i++) {

System.out.print(a[i]+ " ");

}

}

static void rotate(int a[], int n,int k) // method for rotating the elements left

{

System.out.print("\nAfter rotating "+ k +" index left the content of array : ");

for(int i=0;i<n;i++)

{

// a[i] = a[ ( i + k)%n ];

System.out.print( a[ ( i + k)%n ]+" "); // here we are taking nod n beacuse if our left rotaion ie. k value is greater than n then make it zero

}

}

public static void main(String args[])

{

int [] array1 = {1 , 2, 3, 4, 5, 6 ,7 ,8 ,9, 10};

int n1=array1.length ; // size of array

System.out.print("Array before reversing the elements : ");

for(int i=0;i<n1;i++)

{

System.out.print(array1[i]+ " ");

}

reverse(array1, n1); // method calling for reverse the array

int [] array2 ={10 ,20 ,30,40 ,50 ,60};

int n2=array2.length ;

int k= 3 ; // rotating the array by k index left

System.out.print("\nArray before rotating the elements left : ");

for(int i=0;i<n2;i++)

{

System.out.print(array2[i] + " ");

}

rotate(array2, n2, k); // method calling for rotate the array left

}

}

image of output

for any query please ask in the comments section.

Thanks.

Add a comment
Know the answer?
Add Answer to:
Add reverse() method which reverses the content of array without using additional array. rotate(k) method which...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • pls help, idk whats wrong with this Add the reverse() method which reverses the content of...

    pls help, idk whats wrong with this Add the reverse() method which reverses the content of array without using additional array and the rotate(k) method which rotates left the content of array without using additional array by k elements. import java.util.*; * Implementation of the ADT List using a fixed-length array. * * if insert is successful returns 1, otherwise 0; * for successful insertion: * list should not be full and p should be valid. * * if delete...

  • Add the following method to xxxxxp3: // deletes x from sorted list k if exist, k...

    Add the following method to xxxxxp3: // deletes x from sorted list k if exist, k = 0, 1, 2 private void delete(x, k) // returns position of x in sorted list k if exist otherwise, -1. k = 0, 1, 2 private int search(x, k) import java.util.Scanner; class xxxxxp3{ private node[] head = new node[3]; private class node{ int num; node link; node(int x){ num=x; link = null; } } public void prtlst(int k){ System.out.printf("\nContents of List-%d:",k); for(node cur...

  • 2. Use hashing (solve_with_Hash(int[] array, int k)) Initialize a counter variable to O: Insert a...

    2. Use hashing (solve_with_Hash(int[] array, int k)) Initialize a counter variable to O: Insert all elements of array in a hashtable For every element in array: counter0 a. b. c. .Look for array[i] . Look for array [幻 + k in the hash map, if found then increment counter. -k in the hash map, if found then increment counter. Remove arrayli] from hash table. d. return counter For example: Input : array[] {1, 5, 3, 4, 2), k 3 Output:...

  • Fix the errors in C code #include <stdio.h> #include <stdlib.h> void insertAt(int *, int); void Delete(int...

    Fix the errors in C code #include <stdio.h> #include <stdlib.h> void insertAt(int *, int); void Delete(int *); void replaceAt(int *, int, int); int isEmpty(int *, int); int isFull(int *, int); void removeAt(int *, int); void printList(int *, int); int main() { int *a; int arraySize=0,l=0,loc=0; int choice; while(1) { printf("\n Main Menu"); printf("\n 1.Create list\n 2.Insert element at particular position\n 3.Delete list.\n4. Remove an element at given position \n 5.Replace an element at given position\n 6. Check the size of...

  • Question 1: Fix the 2D dynamic array initialization in following code #include <iostream> using namespace std;...

    Question 1: Fix the 2D dynamic array initialization in following code #include <iostream> using namespace std; int main(){    int rows = 5; int cols = 5; int x;    int** arr = new int[rows][cols]    cin >> x; arr[x][x] = x; cout << "arr[x][x] = " << arr[x][x];    return 0; } Question 2: Fix the code to initialize the 2D array elements to x #include <iostream> using namespace std; int main(){    int rows; int cols; int x;...

  • Java deleting from an array // arrayDelete        //        // delete the value...

    Java deleting from an array // arrayDelete        //        // delete the value in the array at position k        // positions are numbered starting with 0        // elements k+1 through N-1 are moved 'down' one position        // to close the space left by deleting element k        // set element N-1 to -99        // preconditions: 0 <= k <= N-1        //    public static void arrayDelete(...

  • ava deleting from an array // arrayDelete        //        // delete the value...

    ava deleting from an array // arrayDelete        //        // delete the value in the array at position k        // positions are numbered starting with 0        // elements k+1 through N-1 are moved 'down' one position        // to close the space left by deleting element k        // set element N-1 to -99        // preconditions: 0 <= k <= N-1        //    public static void arrayDelete(...

  • using c++ 13 do pretty much whatever they want Exercise: Array Resizing You will create an...

    using c++ 13 do pretty much whatever they want Exercise: Array Resizing You will create an array manipulation program that allows the user is to pre much whatever meant to ananas Wananching the program the user will passat are the contains a set of value and that w 2 Check to see the could be opened at the program was not opened the continue 3. Create an array and with the values from Presente en de h and powermany reded...

  • Our 1st new array operation/method is remove. Implement as follows: public static boolean remove( int[] arr,...

    Our 1st new array operation/method is remove. Implement as follows: public static boolean remove( int[] arr, int count, int key ) { 1: find the index of the first occurance of key. By first occurance we mean lowest index that contains this value. hint: copy the indexOf() method from Lab#3 into the bottom of this project file and call it from inside this remove method. The you will have the index of the value to remove from the array 2:...

  • To the HighArray class in the highArray.java, add a method called getMax() that returns the value...

    To the HighArray class in the highArray.java, add a method called getMax() that returns the value of the highest key in the array, or -1 if the array is empty. Add some code in main() to exercise this method. You can assume all the keys are positive numbers. // highArray.java class HighArray { private long[] a; private int nElems;    public HighArray(int max)    { a = new long[max];    nElems = 0; } public boolean find(long searchKey) { int...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT